在R中如何基于外部列表使用mutate创建0/1标记新列?
解决方法
你可以结合dplyr的mutate函数和%in%运算符实现需求,%in%用来判断元素是否存在于目标列表中,再通过as.integer()将逻辑值(TRUE/FALSE)转为1/0:
# 先加载dplyr包 library(dplyr) # 你的原始数据 my_df <- data.frame(A = 1:4, B = c('a','b','c','d')) target_list <- c('c','d','a') # 建议不要用list作为变量名,避免和内置函数冲突 # 创建新列 my_df <- my_df %>% mutate(list_column = as.integer(B %in% target_list)) # 查看结果 print(my_df)
运行后会得到你期望的输出:
A B list_column 1 1 a 1 2 2 b 0 3 3 c 1 4 4 d 1
补充说明
- 把变量名从
list改成target_list是因为list是R的内置函数,用它做变量名可能引发不必要的冲突。 - 如果你不想用
as.integer(),也可以用ifelse()实现,效果一致:mutate(list_column = ifelse(B %in% target_list, 1, 0))
内容的提问来源于stack exchange,提问作者Aryh
相关产品推荐
相关产品推荐

