You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用for循环基于多列及列标签创建R数据框新列?

解决方案

方法一:for循环实现(满足你的需求)

你之前的代码问题在于没有正确引用循环变量对应的列,且未累积拼接结果。以下是可行的for循环写法:

# 初始化新列fruits为空字符串
stuff$fruits <- ""

# 定义需要处理的水果列名称向量
fruits1 <- c('banana','apple')

# 遍历每个水果列
for (fruit in fruits1) {
  # 定位当前列值为1的行,将列名拼接到fruits列的对应位置
  stuff$fruits[stuff[[fruit]] == 1] <- paste0(stuff$fruits[stuff[[fruit]] == 1], fruit)
}

# 将未拼接任何内容的空字符串替换为"0"
stuff$fruits[stuff$fruits == ""] <- "0"

运行这段代码后,stuff数据框就会生成符合要求的fruits列。

方法二:向量化方法(更适合大规模数据集)

如果你的数据集行数/列数极多,for循环效率会偏低,推荐用apply实现向量化操作,速度更快:

fruits1 <- c('banana','apple')
stuff$fruits <- apply(stuff[, fruits1], 1, function(row) {
  # 提取当前行值为1的列名
  selected_fruits <- names(row)[row == 1]
  # 如果没有选中的水果则返回"0",否则拼接列名
  if (length(selected_fruits) == 0) "0" else paste(selected_fruits, collapse = "")
})

验证结果

运行上述任意一种方法后,查看stuff即可得到你想要的输出:

> stuff
   banana apple bike car      fruits
1       1     0    1   0      banana
2       0     0    1   0           0
3       1     0    0   0      banana
4       1     1    1   0 bananaapple
5       0     1    1   0       apple
6       0     0    1   0           0
7       1     0    1   1      banana
8       0     1    0   1       apple
9       1     1    0   0 bananaapple
10      1     1    0   0 bananaapple

内容的提问来源于stack exchange,提问作者camtastic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 20:22:39