Merge multiple data frames in different list

Viewed 59

I want to merge one df, with multiple logical vector. here's an example of what I want:

a <- c(1, 2, 3, 4, 5)
b <- c(1.1, 5.4, 9.3, 6.1 ,4.5)
df <- data.frame(cbind(a,b))
df1 <- data.frame(cbind(a,b))
df2 <- data.frame(cbind(a,b))
list1 <- list(df, df1, df2)

In my data, df1 and df2 are different than df but it's easier. I have my logical vector and I want to cbind them with the first df of the first list.

vc <- c(TRUE, FALSE, TRUE, TRUE,FALSE)
vc1 <- c(FALSE, FALSE, TRUE, TRUE, FALSE)
vc2 <- c(TRUE, TRUE, TRUE, TRUE, TRUE)
list2 <- list(vc, vc1, vc2)

I know how to do it one at a time.

list2[[1]] <- cbind(vc, df)
list2[[2]] <- cbind(vc1, df)
list2[[3]] <- cbind(vc2, df)

So the final result will be:

list2
[[1]]
     vc a   b
1  TRUE 1 1.1
2 FALSE 2 5.4
3  TRUE 3 9.3
4  TRUE 4 6.1
5 FALSE 5 4.5

[[2]]
    vc1 a   b
1 FALSE 1 1.1
2 FALSE 2 5.4
3  TRUE 3 9.3
4  TRUE 4 6.1
5 FALSE 5 4.5

[[3]]
   vc2 a   b
1 TRUE 1 1.1
2 TRUE 2 5.4
3 TRUE 3 9.3
4 TRUE 4 6.1
5 TRUE 5 4.5

But I really have a lot of data and it will take me "years" to do it.

3 Answers

You can use lapply here :

a <- c(1, 2, 3, 4, 5)
b <- c(1.1, 5.4, 9.3, 6.1 ,4.5)
df <- data.frame(a,b)

vc <- c(TRUE, FALSE, TRUE, TRUE,FALSE)
vc1 <- c(FALSE, FALSE, TRUE, TRUE, FALSE)
vc2 <- c(TRUE, TRUE, TRUE, TRUE, TRUE)
list2 <- list(vc, vc1, vc2)

lapply(list2, function(l) cbind(l, df))
#> [[1]]
#>       l a   b
#> 1  TRUE 1 1.1
#> 2 FALSE 2 5.4
#> 3  TRUE 3 9.3
#> 4  TRUE 4 6.1
#> 5 FALSE 5 4.5
#> 
#> [[2]]
#>       l a   b
#> 1 FALSE 1 1.1
#> 2 FALSE 2 5.4
#> 3  TRUE 3 9.3
#> 4  TRUE 4 6.1
#> 5 FALSE 5 4.5
#> 
#> [[3]]
#>      l a   b
#> 1 TRUE 1 1.1
#> 2 TRUE 2 5.4
#> 3 TRUE 3 9.3
#> 4 TRUE 4 6.1
#> 5 TRUE 5 4.5

If you intended to use all objects you provided: Put vectors and data frames into lists and cbind them one by one using Map.

Map(cbind, vc=list(vc, vc1, vc2), list(df, df1, df2))
# [[1]]
#      vc a   b
# 1  TRUE 1 1.1
# 2 FALSE 2 5.4
# 3  TRUE 3 9.3
# 4  TRUE 4 6.1
# 5 FALSE 5 4.5
# 
# [[2]]
#      vc a   b
# 1 FALSE 1 1.1
# 2 FALSE 2 5.4
# 3  TRUE 3 9.3
# 4  TRUE 4 6.1
# 5 FALSE 5 4.5
# 
# [[3]]
#     vc a   b
# 1 TRUE 1 1.1
# 2 TRUE 2 5.4
# 3 TRUE 3 9.3
# 4 TRUE 4 6.1
# 5 TRUE 5 4.5

An option with bind_cols and map

library(purrr)
map(list2, ~ bind_cols(l = .x, df))
Related