在R语言中基于字符串顺序生成对应数值列的实现方法
解决方案
步骤说明
通过R语言的stringr和tidyr包可完成数据转换,核心步骤如下:
- 拆分
Rank列的分号分隔内容为独立条目 - 按条目顺序分配对应分数(首个条目得5分,依次递减至1分)
- 将长格式数据转换为所需的宽格式列结构
代码实现
# 加载必要工具包 library(stringr) library(tidyr) # 示例输入数据 df <- structure(list(Rank = "Shifting angler preferences and behaviors;Increasing effort and fishing power;R3 (Recruitment, Retention, and Reactivation);Economic impacts;Climate change;"), row.names = c(NA, -1L), class = "data.frame") # 拆分Rank列,提取5个有效问题条目 df[, paste0("item_", 1:5)] <- str_split(df$Rank, ";", simplify = TRUE)[, 1:5] # 转换为长格式并计算对应分数 long_df <- df %>% pivot_longer(cols = starts_with("item_"), names_to = "order", values_to = "issue") %>% mutate(score = 6 - as.integer(str_remove(order, "item_"))) # 转换为宽格式,生成最终列结构 final_df <- long_df %>% pivot_wider(names_from = issue, values_from = score) # 查看处理结果 print(final_df)
最终效果
处理后的数据将生成5个对应列,每个列名是原Rank中的问题条目,列值为其对应的分数:
Shifting angler preferences and behaviors:5分Increasing effort and fishing power:4分R3 (Recruitment, Retention, and Reactivation):3分Economic impacts:2分Climate change:1分
内容的提问来源于stack exchange,提问作者David Smith
相关产品推荐
相关产品推荐

