简体   繁体   中英

R Map through list of data.frames and change column types

I am pretty new to R and kinda desperate, since I have been working on this problem for quite some time now.

I have a list of dataframes:

df1 <- data.frame(na = c("bla", "foo", "bar", "baz"), tmp = c(1,2,5,6), tf = c(2.2, 3.4, 5.6, 7.7))
df2 <- data.frame(na2 = c("blu", "oof", "bar", "baz"), tmp = c(7,8,9,10), tf = c(1.1, 3.3, 2.5, 5.7))

listy <- list(df1, df2)

All I want to do is to change every single column of the dataframes within the list to character. I tried

listy %>% map(., ~ mutate(.x, across(everything(), as.character(.)))) -> listy2

listy %>% mutate(across(everything(.,), as.numeric())) -> listy2 listy2<- map(listy, ~.x %>% mutate(across(everything(.x), as.numeric(.,))))

But it doesn't work.

Where is the error?

You got very close - when using across you either pass the function (without () ) or a purrr style formula using ~ :

library(tidyverse)

df1 <- data.frame(na = c("bla", "foo", "bar", "baz"), tmp = c(1,2,5,6), tf = c(2.2, 3.4, 5.6, 7.7))
df2 <- data.frame(na2 = c("blu", "oof", "bar", "baz"), tmp = c(7,8,9,10), tf = c(1.1, 3.3, 2.5, 5.7))

listy <- list(df1, df2)

listy_2 <- listy %>% map(~ mutate(.x, across(everything(), as.character))) 
# or
listy_3 <- listy %>% map(~ mutate(.x, across(everything(), ~as.character(.x)))) 

listy[[1]]$tmp
#> [1] 1 2 5 6

listy_2[[1]]$tmp
#> [1] "1" "2" "5" "6"

listy_3[[1]]$tmp
#> [1] "1" "2" "5" "6"

Created on 2021-04-22 by the reprex package (v1.0.0)

Though the question is tagged purrr , here is a base R solution.

listy <- Map(function(x) {x[] <- lapply(x, as.character); x}, listy)

str(listy)
#List of 2
# $ :'data.frame':  4 obs. of  3 variables:
#  ..$ na : chr [1:4] "bla" "foo" "bar" "baz"
#  ..$ tmp: chr [1:4] "1" "2" "5" "6"
#  ..$ tf : chr [1:4] "2.2" "3.4" "5.6" "7.7"
# $ :'data.frame':  4 obs. of  3 variables:
#  ..$ na2: chr [1:4] "blu" "oof" "bar" "baz"
#  ..$ tmp: chr [1:4] "7" "8" "9" "10"
#  ..$ tf : chr [1:4] "1.1" "3.3" "2.5" "5.7"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM