r - 遍历数据框列表以创建新列
问题描述
我有一个数据框列表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)
解决方案
我们可以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})
推荐阅读
- android - 使用 Flowables.combineLatest 时出现 MissingBackpressureException
- javascript - 访问对象内部的对象
- performance - 为什么遵循随机单链表的 L2 缓存未命中率在问题大小上不是单调的?
- python - Keras 简单前馈网络输入形状错误
- java - Spring Boot 中 OffsetDateTime 的序列化器/反序列化器
- php - 根据登录的用户在 WordPress 上显示管理面板页面
- macos - drone.io 如何在本地服务器上运行命令
- c - 在推出自己的结构时提供辅助功能
- python - 打开/关闭 LED - GPIO Raspberry pi 3
- python - 将图像文件夹转换为 numpy 数组正在消耗整个 RAM