2

I have a dataframe df looking like this

    A     B     C     D
1   78    12    43    12
2   23    12    42    13
3   14    42    11    99
4   49    94    27    72

I need the first two columns converted into a list which looks exactly like this:

[[1]]
[1] 78 12

[[2]]
[1] 23 12

[[3]]
[1] 14 42

[[4]]
[1] 49 94

Basically what

list(c(78, 12), c(23, 12), c(14, 42), c(49, 94)

would do. I tried this

lapply(as.list(1:dim(df)[1]), function(x) df[x[1],])

as well as

lapply(as.list(1:nrow(df)), function(x) df)

But thats slightly different. Any suggestions?

Stophface
  • 8,519
  • 25
  • 87
  • 179

3 Answers3

5

You can try the Map:

Map(c, df$A, df$B)
[[1]]
[1] 78 12

[[2]]
[1] 23 12

[[3]]
[1] 14 42

[[4]]
[1] 49 94
Psidom
  • 195,464
  • 25
  • 298
  • 322
0

In case this is of interest, it is possible to accomplish this with the foreach package:

library(foreach)
foreach(i=seq.int(nrow(df))) %do% (c(df[[i]][1], df[[i]][2]))

foreach returns a list by default. The code runs down the rows and pulls elements from the first and second columns.

An even cleaner to read version:

foreach(i=seq.int(nrow(df))) %do% (df[[i]][1:2])
lmo
  • 36,904
  • 9
  • 50
  • 61
0

Another option is with lapply

lapply(seq_len(nrow(df1)), function(i) unlist(df1[i, 1:2], use.names=FALSE))
#[[1]]
#[1] 78 12

#[[2]]
#[1] 23 12

#[[3]]
#[1] 14 42

#[[4]]
#[1] 49 94
akrun
  • 789,025
  • 32
  • 460
  • 575