如何将同一函数应用于R中的多个数据帧

如何将同一函数应用于R中的多个数据帧,r,for-loop,R,For Loop,我将相同的函数应用于多个数据帧。例如,我想合并df1中的column2和column3。应用此函数后,df1将获得一个名为col2\u col3的新列 df1 <- data.frame(x = rep(3, 5), y = seq(1, 5, 1), ID = letters[1:5]) df2 <- data.frame(x = rep(5, 5), y = seq(2, 6, 1), ID = letters[6:10]) #I define a function: Pas

我将相同的函数应用于多个数据帧。例如,我想合并df1中的column2和column3。应用此函数后,df1将获得一个名为col2\u col3的新列

 df1 <- data.frame(x = rep(3, 5), y = seq(1, 5, 1), ID = letters[1:5])
 df2 <- data.frame(x = rep(5, 5), y = seq(2, 6, 1), ID = letters[6:10])
#I define a function:
PasteTwoColumn <- function(x) 
{
  x$col2_col3 <- paste(x[,2], x[,3], sep = "_")
  return(x)
}
#apply the function to the df1, it works.
df1 <- PasteTwoColumn(df1)
# but I failed by an lappy function, because it returns a list, not the dataframe
mylist <- list(df1, df2) 
result <- lapply(mylist, PasteTwoColumn)

df1我们可以将数据集保存在
list
中,并使用
lappy

lst1 <- lapply(list(df1, df2), PasteTwoColumn)
或者,我们也可以使用
ls

lst1 <- lapply(mget(ls(pattern = '^df\\d+$')), PasteTwoColumn)

如果我们需要为
循环使用

for(obj in paste0("df", 1:100)) {
      assign(obj,  PasteTwoColumn(get(obj)))
  }

最后一个[循环]正是我想要的。谢谢你在很多方面给我看。我学到了很多。
list2env(lst1, .GlobalEnv) #not recommended though
for(obj in paste0("df", 1:100)) {
      assign(obj,  PasteTwoColumn(get(obj)))
  }