I have a column in a df that has a long string of characters. I need to update a different column when a certain part of the string matches a set. For example:
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)
I want to update the location to 56.32 only for the Folder which contain "A-BC-12-3". So far I tried
df$Location[df$Folder %>% str_subset(pattern = "A-BC-12-3")] <- "56.32"
but only get this error message:
Error in $<-.data.frame
(*tmp*
, Location, value = c("NA", "NA", "NA", :
replacement has 4 rows, data has 3
Any suggestions?
CodePudding user response:
You may try
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
Or using grepl
df$Location[grepl("A-BC-12-3", df$Folder)] <- "56.32"