r - 通过为每列动态添加前缀来更新列值
问题描述
我有一个 for 循环,我在其中创建一个数据框。因为该数据框在每一轮中将采用不同的形状。同时我在每一轮中创建字符串向量,其中向量的长度等于数据的列数框架。作为随机轮次中的示例,数据框是merged_
,字符串向量是out.names
merged_ <- data.frame(V8 = c(19, 19, 1, 4, 4, 4),
V9 = c("9P0480", "9P0480", "9P0480", "9P0480", "9P0480", "9P0480"),
V10 = c(0,0,0,0,0,0),
V11 = c(4580,4580,4580,4580,4580,4580))
out.names <- c("hello","hello2","hello3","hello4")
现在我需要通过添加字符串值作为前缀来更新每一列。像这样输出
df_new <- data.frame(V8 = c("hello:19", "hello:19", "hello:1", "hello:4", "hello:4", "hello:4"),
V9 = c("hello2:9P0480", "hello2:9P0480", "hello2:9P0480", "hello2:9P0480", "hello2:9P0480", "hello2:9P0480"),
V10 = c("hello3:0","hello3:0","hello3:0","hello3:0","hello3:0","hello3:0"),
V11 = c("hello4:4580","hello4:4580","hello4:4580","hello4:4580","hello4:4580","hello4:4580"))
V8 V9 V10 V11
1 hello:19 hello2:9P0480 hello3:0 hello4:4580
2 hello:19 hello2:9P0480 hello3:0 hello4:4580
3 hello:1 hello2:9P0480 hello3:0 hello4:4580
4 hello:4 hello2:9P0480 hello3:0 hello4:4580
5 hello:4 hello2:9P0480 hello3:0 hello4:4580
6 hello:4 hello2:9P0480 hello3:0 hello4:4580
到目前为止我尝试的是,尝试使用 for 循环更新每一列。
for (col in 1:ncol(merged_)) {
merged_[,col] <- paste0(out.names[col],":",merged_[,col])
}
这是我尝试上述代码时的错误
(merged_, , col) 中的错误
[.data.table
:j([...] 内的第二个参数)是单个符号,但未找到列名 'col'。也许您打算使用 DT[,..col] 或 DT[,col,with=FALSE]。与 data.frame 的这种差异是经过深思熟虑的,并在 FAQ 1.1 中进行了解释。
这可以通过使用一些矢量化方法来解决,而不使用 for 循环。
解决方案
我们可以按列使用Map
和paste
值。out.names
merged_
merged_[] <- Map(paste, out.names, merged_, sep = ":")
merged_
# V8 V9 V10 V11
#1 hello:19 hello2:9P0480 hello3:0 hello4:4580
#2 hello:19 hello2:9P0480 hello3:0 hello4:4580
#3 hello:1 hello2:9P0480 hello3:0 hello4:4580
#4 hello:4 hello2:9P0480 hello3:0 hello4:4580
#5 hello:4 hello2:9P0480 hello3:0 hello4:4580
#6 hello:4 hello2:9P0480 hello3:0 hello4:4580
这类似于map2
in purrr
。
merged_[] <- purrr::map2(out.names, merged_, paste, sep = ":")
推荐阅读
- python - 使用 django,python 从 Okta 登录后读取 SAML 用户 ID
- python - C++ 高效解析 Python 数组字符串
- node.js - nodejs单元测试PubSub.publish不发送数据
- amazon-web-services - 基于源 IP 的 AWS 安全组规则
- powershell - 如何从 Windows 资源管理器在后台(无窗口)运行 PowerShell 脚本?
- java - 使用 ItemTouchHelper 从 RecyclerView 中删除项目时引发 UnsupportedOperationException
- node.js - 如何使用 Mongoose 在 mongodb 中查找或获取随机记录或文档
- reactjs - 如果可以有多个处理程序,如何不每次都为处理程序创建一个函数?
- java - 我如何获取内部音频的字节 [] pcmData (Xt Audio for Java)
- html - 如何使图像和文字在同一行?