如何用R的Mutate、case_when、paste生成fruits_name列
问题描述
我希望通过mutate生成fruits_name列,规则是当apple、banana、orange列的值为1时,将对应列名拼接成该列的内容。例如当apple和orange列值为1时,fruits_name为“apple orange”。示例表格如下:
| apple | banana | orange | fruits_name |
|---|---|---|---|
| 1 | 0 | 1 | apple orange |
| 1 | 0 | 0 | apple |
| 1 | 0 | 1 | apple orange |
| 1 | 1 | 1 | apple banana orange |
解决方案
方法1:使用dplyr(推荐)
借助dplyr的行处理功能,结合stringr实现列名拼接:
library(dplyr) library(stringr) # 构造示例数据 df <- tibble( apple = c(1, 1, 1, 1), banana = c(0, 0, 0, 1), orange = c(1, 0, 1, 1) ) # 生成目标列 df <- df %>% rowwise() %>% mutate(fruits_name = str_c(names(.)[c_across(apple:orange) == 1], collapse = " ")) %>% ungroup()
rowwise():指定按行处理数据c_across(apple:orange):选中需要判断的三列names(.)[c_across(...) == 1]:筛选出当前行值为1的列名str_c(..., collapse = " "):将列名用空格拼接成字符串
方法2:基础R实现
如果不依赖dplyr,可以用apply逐行处理:
# 构造示例数据 df <- data.frame( apple = c(1, 1, 1, 1), banana = c(0, 0, 0, 1), orange = c(1, 0, 1, 1) ) # 生成目标列 df$fruits_name <- apply(df[, c("apple", "banana", "orange")], 1, function(x) { paste(names(x)[x == 1], collapse = " ") })
处理结果
运行上述代码后,得到的结果与示例表格完全一致:
| apple | banana | orange | fruits_name |
|---|---|---|---|
| 1 | 0 | 1 | apple orange |
| 1 | 0 | 0 | apple |
| 1 | 0 | 1 | apple orange |
| 1 | 1 | 1 | apple banana orange |
内容的提问来源于stack exchange,提问作者Glen P Janson
相关产品推荐
相关产品推荐

