我有一个数据列表,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)
发布于 2019-04-04 07:40:47
我们可以使用lapply
循环list
元素,使用transform
创建paste
ed组件(假设我们只有3列且列名是静态的)。
lapply(DFList, transform, X4 = paste0(X1, X2, X3))
如果我们有可变列
lapply(DFList, function(x) {x$newCol <- do.call(paste0, x); x})
https://stackoverflow.com/questions/55519947
复制相似问题