如果其他列在r中的字符串中有特定的字符集,如何更新行值



我在df中有一列有一个长字符串。当字符串的某个部分与集合匹配时,我需要更新另一列。例如:

Folder <- c("Computer-A-BC-12-3","Computer-A-DC-45-6","Computer-A-BC-12-3")
Location <- c("NA","NA","NA")
df <-data.frame(Folder, Location)

我只想将文件夹的位置更新到56.32;A-BC-12-3";。到目前为止,我尝试了

df$Location[df$Folder %>% str_subset(pattern = "A-BC-12-3")] <- "56.32"

但只得到以下错误消息:$<-.data.frame中的错误(*tmp*,Location,value=c("NA","NA"、"NA":替换有4行,数据有3个

有什么建议吗?

您可以尝试

df$Location[df$Folder %in% (df$Folder %>% str_subset(pattern = "A-BC-12-3"))] <- "56.32" 
Folder Location
1 Computer-A-BC-12-3    56.32
2 Computer-A-DC-45-6       NA
3 Computer-A-BC-12-3    56.32

或使用grepl

df$Location[grepl("A-BC-12-3", df$Folder)] <- "56.32" 

最新更新