Suppose I have a list of two dataframes.
Name1 <- c("Jon", "Bill", "Maria")
Age1 <- c(23, 41, 32)
df1 <- data.frame(Name1, Age1)
Name2 <- c("Sally", "Tom")
Age2 <- c(25, 32)
Height <- c(56, 55)
df2 <- data.frame(Name2, Age2, Height)
list1 <- list(df1, df2)
list1
[[1]]
Name1 Age1
1 Jon 23
2 Bill 41
3 Maria 32
[[2]]
Name2 Age2 Height
1 Sally 25 56
2 Tom 32 55
I also have another list for the column names, that differ with each dataframe as they have inconsistent column numbers.
list2 <- list( c("Names", "Age"), c("Names", "Age", "Height"))
list2
[[1]]
[1] "Names" "Age"
[[2]]
[1] "Names" "Age" "Height"
How can I assign the values in list2 as the column names for list1?
CodePudding user response:
You can do it with a simple for loop that iterates along both lists simultaneously:
for (i in seq_along(list1)){
colnames(list1[[i]]) <- list2[[i]]
}
# [[1]]
# Names Age
# 1 Jon 23
# 2 Bill 41
# 3 Maria 32
#
# [[2]]
# Names Age Height
# 1 Sally 25 56
# 2 Tom 32 55
If you had the same number of columns in each df and a vector of names, then use lapply
to make it even simpler:
lapply(list1, setNames, list2)
See Changing Column Names in a List of Data Frames in R for more info.