首页 > 解决方案 > 遍历数据框列表以创建新列

问题描述

我有一个数据框列表DFList。对于DFList我想创建一个新列中的每个数据框X4

Small Example

X1 <- c(1,2,3,"X","Y")
X2 <- c(100,200,130,120,150)
X3 <- c(1000,250,290,122,170)
DF1 <- data.frame(X1,X2,X3)

X1 <- c(5,6,4,3,9)
X2 <- c(105,205,150,125,175)
X3 <- c(1500,589,560,512,520)
DF2 <- data.frame(X1,X2,X3)

DFList <- list(DF1,DF2)
names(DFList) <- c("DF1","DF2")
DFList

为了通过组合 X1、X2 和 X3 列的值来创建新列,我创建了以下函数。

MyFUN <- function(V) {
  X4 <- paste(V[1],":",V[2],"-",V[3], sep = "")
  return(X4)
}

但是,我无法成功运行此功能...我尝试了以下操作,但未将所需的 X4 列添加到列表中包含的数据帧中。

print(DFList)

for (DF in DFList){
  for (num in (0:length(DFList))){
    DF["X4"] <- lapply(DF[num], FUN = MyFUN)
  }
}

print(DFList)

标签: rlistlapply

解决方案


我们可以lapply用来循环遍历list元素并transform创建pasteed 组件(假设我们只有 3 列并且列名是静态的

lapply(DFList, transform, X4 = paste0(X1, X2, X3))

如果我们有可变列

lapply(DFList,  function(x) {x$newCol <- do.call(paste0, x); x})

推荐阅读