0

I'm trying to add columns to a data frame dinamycally using cbind and lapply

to illustrate a problem I will do it wihtout lapply

> c1 <- c(1,2)
> c2 <- c(3,4)
> 
> source = data.frame(c1, c2)
> 
> source
  c1 c2
1  1  3
2  2  4
> 

> names = c("c1", "c2")

> merged2 <- data.frame(matrix(nrow = 2))
> merged2 <- cbind(merged2, source[[ names[1] ]])
> merged2 <- cbind(merged2, source[[ names[2] ]])
> 
> merged2 

  matrix.nrow...2. source[[names[1]]] source[[names[2]]]
1               NA                  1                  3
2               NA                  2                  4

This part work almost fine. the only thing I need here is to remove first column, but I believe there is better way not to create it at all which I'm not aware of.

but version with lapply produces not expected result:

> merged2 <- data.frame(matrix(nrow = 2))
> lapply(names, function(x) merged2 = cbind(merged2, source[[x]]) )
[[1]]
  matrix.nrow...2. source[[x]]
1               NA           1
2               NA           2

[[2]]
  matrix.nrow...2. source[[x]]
1               NA           3
2               NA           4

> merged2 
  matrix.nrow...2.
1               NA
2               NA
> 

i tried it different way and it's not what I'm getting when cbind'ing "manually"

> merged2 <- data.frame(matrix(nrow = 2))
> merged2 <- lapply(names, function(x) merged2 = cbind(merged2, source[[x]]) )
> merged2 
[[1]]
  matrix.nrow...2. source[[x]]
1               NA           1
2               NA           2

[[2]]
  matrix.nrow...2. source[[x]]
1               NA           3
2               NA           4

Probably I misuse lapply, please advice

thanks in advance, --Oleg

Oleg K
  • 1
  • 1

0 Answers0