How to do a mutate_all within a list of dataframes to remove bad data

Viewed 77

Sample data:

dat1 <- structure(list(id = 1:3, des.1 = 4:6, x = 7:9, not = 10:12), class = "data.frame", row.names = c(NA,-3L))
dat2 <- structure(list(id = 1:3, descript = 4:6, y = 7:9, yes = 10:12), class = "data.frame", row.names = c(NA,-3L))
dat3 <- structure(list(id = 1:3, description = 4:6, x = 7:9, X4 = 10:12), class = "data.frame", row.names = c(NA,-3L))
dat1[1,2] <- "ERROR"
dat2[2,1] <- "ERROR"
dat_list <- list(dat1, dat2, dat3)

How can I set all instances of 'ERROR' to 0 within this list of dataframe? If possible, a plyr solution would be preferred.

Many thanks.

1 Answers

You can use map to iterate over list :

library(dplyr)
library(purrr)

map(dat_list, ~.x %>% mutate_all(~replace(., . == 'ERROR', 0)) %>% type.convert)

In new dplyr you can use across :

map(dat_list, ~.x %>% 
               mutate(across(everything(), ~replace(., . == 'ERROR', 0))) %>% 
               type.convert)

In base R, we can use lapply :

lapply(dat_list, function(x) {x[x == 'ERROR'] <- 0;type.convert(x)})

#[[1]]
#  id des.1 x not
#1  1     0 7  10
#2  2     5 8  11
#3  3     6 9  12

#[[2]]
#  id descript y yes
#1  1        4 7  10
#2  0        5 8  11
#3  3        6 9  12

#[[3]]
#  id description x X4
#1  1           4 7 10
#2  2           5 8 11
#3  3           6 9 12
Related