Beeba
Beeba

Reputation: 642

lapply with second iteration in R

I have two lists, one containing 2 data.frames and the other containing 2 vectors.

I need to set the column names in the data.frames to the vectors in the other list, can't seem to wrap my head around how to do that with lapply.

reproducible example:

set.seed(1)
df1 <- data.frame(
  X = sample(1:10),
  Y = sample(c("yes", "no"), 10, replace = TRUE)
)

df2 <- data.frame(
    Z = sample(LETTERS,10),
    X = sample(1:10),
    Y = sample(c("yes", "no"), 10, replace = TRUE)
)
dataframes <- list(df1, df2)
columns <- list(c("numbers", "boolean"),c("letters", "numbers", "boolean"))

Data frames have different number of columns and column names are very different in my original data. What i've been trying to do is to map the columns list as colnames for the data frames using lapply but I need to iterate through columns and I don't know how to do that.

Upvotes: 0

Views: 71

Answers (2)

akrun
akrun

Reputation: 887158

With tidyverse, we can use map2

library(tidyverse)
map2(dataframes, columns, set_names)
#[[1]]
#   numbers boolean
#1        3     yes
#2        4     yes
#3        5      no
#4        7     yes
#5        2      no
#6        8     yes
#7        9      no
#8        6      no
#9       10     yes
#10       1      no

#[[2]]
#   letters numbers boolean
#1        Y       5      no
#2        F       6      no
#3        P       4      no
#4        C       2      no
#5        Z      10      no
#6        I       8      no
#7        A       9     yes
#8        H       1     yes
#9        X       7      no
#10       V       3      no

Upvotes: 2

IceCreamToucan
IceCreamToucan

Reputation: 28685

Map(setNames, dataframes, columns)

# [[1]]
#    numbers boolean
# 1        3     yes
# 2        4     yes
# 3        5      no
# 4        7     yes
# 5        2      no
# 6        8     yes
# 7        9      no
# 8        6      no
# 9       10     yes
# 10       1      no
# 
# [[2]]
#    letters numbers boolean
# 1        Y       5      no
# 2        F       6      no
# 3        P       4      no
# 4        C       2      no
# 5        Z      10      no
# 6        I       8      no
# 7        A       9     yes
# 8        H       1     yes
# 9        X       7      no
# 10       V       3      no

Upvotes: 6

Related Questions