What is a good way to replace a certain character in a list in R? I tend to prefer the tidyverse functions str_replace_all and map, but I can also use base functions gsub and lapply.
Lets create a list:
df1 <- as.data.frame(iris)
df2 <- as.data.frame(iris)
df3 <- as.data.frame(iris)
iris_list <- list(df1, df2, df3)
I want to replace all mentions to "virginica" to "flower". So I create a custom function:
my_fun <- function(my_list){
str_replace_all(my_list, pattern = "virginica", replacement = "flower")
}
The function str_replace needs a vector as its input. But when I try to use map to iterate over the elements of the list, I get an error: "argument is not an atomic vector; coercing"
map(.x = iris_list, .f = my_fun)
CodePudding user response:
A possible solution:
library(tidyverse)
map(iris_list, ~ mutate(.x, Species = str_replace(Species, "virginica", "flower")))