I'm riffing off the question asked "I don't know how to do this for loop with Purrr" from 2019-02-02.
I was trying to use the answer to this question to figure out an approach for a related, but somewhat different problem. The solution to the problem indicates to map the modifier which contains the "old" strings (strings to be replaced" and "new" strings" and map over a vector.
I want to do something similar with a dataframe. But instead of mapping over a single vector, I want to replace strings in colB and colC in a dataframe.
For my solution:
- I want to reference the column by their names,
- the columns will not always be adjacent, so I don't want to use a solution like "colB:colC" (although that would be handy to know how to do!)
df <- data.frame(
stringsAsFactors = FALSE,
id = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L),
colA = c("caacute","caacute","caacute",
"capitaacute","mara","mara","capitaacute","capitaacute","capitaacute"),
colB = c("mara","mara","pido", "pido","caacute","pido","caacute","intreacute","intreacute"),
colC = c("pido","pido","pido", "pido","caacute","pido","caacute","empty","kitten")
)
This is the result I'm looking for:
dfFinal <- data.frame(
stringsAsFactors = FALSE,
id = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L),
colA = c("caacute","caacute","caacute",
"capitaacute","mara","mara","capitaacute","capitaacute","capitaacute"),
colB = c("all your life", "all your life", "you were only", "you were only", "caacute", "you were only", "caacute", "waiting for this moment", "waiting for this moment"),
colC = c("you were only", "you were only", "you were only", "you were only", "caacute", "you were only", "caacute", "empty", "kitten")
)
Code I copied from a previous question, and my modifications:
# old strings to replace
args_1 <- list('mara', 'pido', 'intreacute')
# new strings
args_2 <- list('all your life','you were only', 'waiting for this moment')
# I want to change colB and colC by using. list_1 and list_2 are 2 different approaches, that didn't work.
list_1 <- list ('colB', 'colC')
list_2 <- c ('colB', 'colC')
# modifier which replaces the old strings with the new strings
modifier <- purrr::map2(args_1, args_2, ~purrr::partial(stringr::str_replace_all, pattern = .x, replacement = .y)) %>%
purrr::reduce(purrr::compose)
- Note: I don't know what this part of the script does
%>% purrr::reduce(purrr::compose)
but when I tried to cobble a solution using this code, I was able to get partway there, so I'm just giving it a go. - Here are some of the approaches I tried but didn't work...
df1 <- df %>%
purrr::map_chr(list_1, modifier)
df1 <- df %>%
purrr::map_chr(list_2, modifier)
Can you help me figure out how to develop an approach that will include:
- List of columns to change
- List of old strings to be replaced
- List of new strings which will replace the list of old strings.
Actually, I'm not married to solving this using purrr, but I'd like to figure out an approach.
Thank you!