So, I have this, and it works
z <- str_replace_all(x, "White", "Example")
Now if I have a string "White House X", I get "Example House X".
What do I do to just get the output as "Example" and get rid of the rest of the string
So, I have this, and it works
z <- str_replace_all(x, "White", "Example")
Now if I have a string "White House X", I get "Example House X".
What do I do to just get the output as "Example" and get rid of the rest of the string
Try
str_replace_all("White House X", ".*White.*", "Example")
though
str_replace("White House X", ".*White.*", "Example")
will also work.
And if it was a column in a data set that has multiple different strings containing "White" ?
I'm trying to use this but I don't know how to do it:
x <- data4 %>%
mutate_if(is.character, str_replace_all,
pattern = '.*White*.',
replacement = 'White')
This works for me.
library(stringr)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
df <- data.frame(A = c(1,2,3),
B = c("Stag White", "Blue", "Color"),
C = c("play White", "black White blue", "white"),
D = c("green", "yellow", "WhitehallWhite"), stringsAsFactors = FALSE)
df
#> A B C D
#> 1 1 Stag White play White green
#> 2 2 Blue black White blue yellow
#> 3 3 Color white WhitehallWhite
df2 <- df %>% mutate_if(is.character, str_replace_all, pattern = ".*White.*", "White")
df2
#> A B C D
#> 1 1 White White green
#> 2 2 Blue White yellow
#> 3 3 Color white White
Created on 2019-05-06 by the reprex package (v0.2.1)
Are you sure your column is character and not a factor?
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.