R语言数据框处理:为未选中属性列填充0的技术需求
R语言数据框:为未选中的展示属性填充0
需求说明
处理数据框时,需要为attr_shown列中未被选为Most_helpful或Least_helpful的属性对应列填充0。具体要求:
- 第1、2、3行的
Link_to_setup_videos列填0 - 第4行的
Non_mobile_device_instructions列填0
示例数据
df <- data.frame( Respondent = rep(8,4), Set= seq(1:4), Least_helpful = c("Customer service phone number", "Customer service phone number", "QR code to online chat","QR code to online chat"), Most_helpful = c("Non-mobile device instructions", "Non-mobile device instructions", "Non-mobile device instructions", "Mobile device instructions"), attr_shown = c("Non-mobile device instructions;Customer service phone number;Link to setup videos", "Mobile device instructions;QR code to online chat;Link to setup videos", "Non-mobile device instructions;QR code to online chat;Link to setup videos", "Mobile device instructions;Non-mobile device instructions;QR code to online chat"), Customer_service_phone_number = c(-1,-1,NA,NA), Non_mobile_device_instructions = c(1,1,1,NA), Link_to_setup_videos = c(NA,NA,NA,NA), Mobile_device_instructions = c(NA,NA,NA,1), QR_code_to_online_chat = c(NA,NA,-1,-1) )
解决方案代码
使用dplyr包实现需求:
library(dplyr) # 转换属性名称格式(空格替换为下划线,匹配数据框列名) clean_attr_name <- function(attr) { gsub(" ", "_", attr) } df_processed <- df %>% rowwise() %>% # 拆分展示属性,筛选出既不是最有用也不是最没用的属性 mutate(target_col = list(setdiff(strsplit(attr_shown, ";")[[1]], c(Most_helpful, Least_helpful)) %>% clean_attr_name())) %>% ungroup() %>% # 为目标列对应行填充0 mutate(across(all_of(unlist(.$target_col)), ~ifelse(row_number() %in% which(sapply(target_col, function(cols) cur_column() %in% cols)), 0, .))) %>% # 移除辅助列 select(-target_col) # 查看处理结果 print(df_processed)
结果验证
处理后的数据框满足需求:
- 第1-3行
Link_to_setup_videos值为0 - 第4行
Non_mobile_device_instructions值为0 - 其余原有值(
1/-1)保持不变
内容的提问来源于stack exchange,提问作者Matt Gehr
相关产品推荐
相关产品推荐

