Reputation: 129
I have a list with around 100 data frames and want to replace the empty cells in a particular column (named Event) of all the data frames in the list with a character. I first tried the following code,
lapply(my_list, function(x) replace(x,is.na(x),"No_Event"))
The above code replaces all the NA into '"No_Event". But I want the replacement of the empty cells in a specific column. Also not sure how to represent the blank cells in the code. The following " " doesn't work.
Then I tried,
lapply(my_list, function(x) transform(x, Event = chartr(" ", 'No_Event', Event))
I understand that the above code replaces a particular letter with the specified character, but not sure how to transform the empty/blank cells of the specific column with a character. Besides, I also tried some other codes, which produce errors. Apologies if the question is very basic and the approach that I followed is wrong.
Thanks
Upvotes: 0
Views: 204
Reputation: 2217
Here is a reproducible example (R Version 4.1.0
)
library(tidyverse)
my_list <- list(
data.frame(a = 1:5, Event = c(6, "", "", 9, ""), c = 11:15),
data.frame(a = 1:5, Event = c("", "", "", 8, 9), c = 16:20)
)
lapply(my_list, FUN = \(x) {
x |> mutate(Event = case_when(Event == "" ~ "No event", TRUE ~ Event))
})
For earlier R versions:
lapply(my_list, FUN = function(x) {
x %>% mutate(Event = case_when(Event == "" ~ "No event", TRUE ~ Event))
})
Upvotes: 1