我在 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)
我只想將包含“A-BC-12-3”的檔案夾的位置更新為 56.32。到目前為止我試過
df$Location[df$Folder %>% str_subset(pattern = "A-BC-12-3")] <- "56.32"
但只收到此錯誤訊息: Error in $<-.data.frame( *tmp*, Location, value = c("NA", "NA", "NA", : 替換有 4 行,資料有 3
有什么建議?
uj5u.com熱心網友回復:
你可以試試
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"
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/376266.html
