apply function to elements of list matching class else return element unchanged

I'd like to use some combination of purrr::map and purrr::possibly to achieve the below. Is this possible?

mixed_list <- list(mtcars, mtcars, letters)

for (i in seq_along(mixed_list)){
  print(i)
  if (class(mixed_list[[i]]) == "data.frame"){
    mixed_list[[i]] <- as.matrix(mixed_list[[i]])
  }
}
#> [1] 1
#> [1] 2
#> [1] 3

This is a job for purrr::map_if().

library(purrr)

mixed_list <- list(mtcars, mtcars, letters)

map(mixed_list, class)
#> [[1]]
#> [1] "data.frame"
#> 
#> [[2]]
#> [1] "data.frame"
#> 
#> [[3]]
#> [1] "character"

output <- map_if(mixed_list, is.data.frame, as.matrix)

map(output, class)
#> [[1]]
#> [1] "matrix" "array" 
#> 
#> [[2]]
#> [1] "matrix" "array" 
#> 
#> [[3]]
#> [1] "character"

Created on 2020-08-10 by the reprex package (v0.3.0)

Thanks a lot! didn't know about these conditional mapping functions

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.