r - 如何将唯一行值更改为 R 中数据框中的另一组唯一行值?
问题描述
我有一个数据框,其中包含来自在线参加我测试的参与者的实验结果。在数据文件中,每个唯一的参与者都由实验结束时随机生成的代码标识。由于通过看起来像乱码的随机代码来识别每个人很麻烦,我想用 Participant_1、Participant_2 等可读标签替换这些代码。
所以我想我需要一段代码来识别数据文件中每个唯一的随机代码,并将它们一个一个替换为参与者标签。但我无法弄清楚,任何帮助将不胜感激。
这是一段代码,显示了我的输出与我想要的输出。请注意,每个参与者都回答了不同数量的问题,因此这不能用作解析它们的简单方法。
Participant_Identifiers <- c(rep("QHDKWEFHWKHFFH", 4), rep("WHWIHFJNWFKWF", 7), rep("HEIFFFBBKQLSD", 3))
Participant_Scores <- c(20, 30, 59, 20, 47, 84, 21, 90,54,78,90,97)
df <- data.frame("Participant_Identifiers" = c(rep("QHDKWEFHWKHFFH", 4), rep("WHWIHFJNWFKWF", 7), rep("HEIFFFBBKQLSD", 3)),
"Participant_Scores" = c(20, 30, 59, 20, 47, 84, 21, 90,54,78,90,97, 35, 67))
df
df_I_want <- data.frame("Participant_Identifiers" = c(rep("Participant_1", 4), rep("Participant_2", 7), rep("Participant_3", 3)),
"Participant_Scores" = c(20, 30, 59, 20, 47, 84, 21, 90,54,78,90,97, 35, 67))
df_I_want
解决方案
这是您可以执行的操作:
# example
ano <- replicate(5, paste(letters[sample(1:25, 12, replace = TRUE)], collapse = ""))
df <- data.frame(pat = sample(ano, 15, replace = TRUE), var = runif(15),
stringsAsFactors = FALSE )
# 1. create another data frame with the id you want
patu <- unique(df$pat)
df_id <- data.frame(pat = patu, id = paste0("Participant_", seq_along(patu)))
# 2. merge with your df
res <- merge(df, df_id)
推荐阅读
- bash - 在 bash 脚本中的一位数字/文本前面添加 0
- github - 如何防止原始 github 令牌过期
- javascript - 如何在 Angular 6 中发送 ajax 请求?
- python - 在打印语句中调用对象名称。我做对了吗?
- git - 从 `git rev-list` 命令输出中排除 `commit ...` 行
- c - 在扩展 asm 输出参数中使用“+”修饰符时输入参数索引?
- java - 比类访问修饰符限制更少的成员访问修饰符有什么用?
- javascript - 如何一次扫描一个条形码?[反应原生相机]
- javascript - 调用脚本时 Javascript 代码返回“未找到”
- android - 如何在最近的应用程序中使屏幕空白但允许屏幕截图