在 R 中查找和替换矩阵单元格中的字符串
Finding and replacing strings in cells of a matrix in R
我正在尝试处理一项调查,其中一个问题要求受访者说出一位朋友的名字。现在我有一个这样的矩阵:
我想将这些结果保存在关系数据库中。我已经为每个人分配了一个唯一的 ID,并希望将答案保存为最后一个 ID。这样 table 看起来像这样:
到目前为止我的代码:
我试过了
df$name %in% df$friends
没有给出任何结果。我现在正在尝试将 for 循环与 str_detect:
一起使用
friends <- df$friends
names <- df$name
for (i in 1:length(names)) {
friends_called <- str_detect(friends, names[i])
id_index <- grep(names[i], df$name)
id <- df$id[id_index]
for (j in 1:length(friends_called)) {
if(friends_called[j] == T) {
df$friends_id[j] <- paste(df$friends_id[j], id, ",", sep="")
}
df$friends <- df$friends_id
但是我有一些问题:
- 没用
- 它使用两个循环,我习惯于编写 python 但我读到我应该在 R
中避免使用它们
- 字符串匹配需要模糊(如果Anna写的是"Jon"而不是"John",应该还是匹配的。
有人对如何解决这个问题有建议吗?
您可以在 tidyverse
中不使用循环来执行此操作,如下所示:
df %>%
mutate(friends = map(friends, ~ df %>%
filter(str_detect(.x,name)) %>%
select(id) %>%
unlist() %>%
paste(collapse = ',')))
给予
id name friends
1 a1d John b2e,c3f
2 b2e Anna a1d
3 c3f Denise
或者使用 base R 你可以使用 sapply:
df$friends <- sapply(friends, function(x) paste(id[str_detect(x,name)],collapse = ','))
我正在尝试处理一项调查,其中一个问题要求受访者说出一位朋友的名字。现在我有一个这样的矩阵:
我想将这些结果保存在关系数据库中。我已经为每个人分配了一个唯一的 ID,并希望将答案保存为最后一个 ID。这样 table 看起来像这样:
到目前为止我的代码:
我试过了
df$name %in% df$friends
没有给出任何结果。我现在正在尝试将 for 循环与 str_detect:
一起使用friends <- df$friends
names <- df$name
for (i in 1:length(names)) {
friends_called <- str_detect(friends, names[i])
id_index <- grep(names[i], df$name)
id <- df$id[id_index]
for (j in 1:length(friends_called)) {
if(friends_called[j] == T) {
df$friends_id[j] <- paste(df$friends_id[j], id, ",", sep="")
}
df$friends <- df$friends_id
但是我有一些问题:
- 没用
- 它使用两个循环,我习惯于编写 python 但我读到我应该在 R 中避免使用它们
- 字符串匹配需要模糊(如果Anna写的是"Jon"而不是"John",应该还是匹配的。
有人对如何解决这个问题有建议吗?
您可以在 tidyverse
中不使用循环来执行此操作,如下所示:
df %>%
mutate(friends = map(friends, ~ df %>%
filter(str_detect(.x,name)) %>%
select(id) %>%
unlist() %>%
paste(collapse = ',')))
给予
id name friends
1 a1d John b2e,c3f
2 b2e Anna a1d
3 c3f Denise
或者使用 base R 你可以使用 sapply:
df$friends <- sapply(friends, function(x) paste(id[str_detect(x,name)],collapse = ','))