Convert all columns of a data frame

Asked

Viewed 810 times

2

I know that to convert a column I can do df$COLUNA <- as.character(df$COLUNA). But my problem is that I need to convert all 80 columns of 18 arranged dataframes into one list. The idea of conversion is that I intend to stack them by bind_rows() and since I won’t be doing operations with the columns, it leaves the format they will be.

2 answers

3


You can use the mutate_all:

For example:

library(tidyverse)
#> Warning: package 'tibble' was built under R version 3.5.2
mtcars <- as_tibble(mtcars)
mtcars %>% mutate_all(as.character)
#> # A tibble: 32 x 11
#>    mpg   cyl   disp  hp    drat  wt    qsec  vs    am    gear  carb 
#>    <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
#>  1 21    6     160   110   3.9   2.62  16.46 0     1     4     4    
#>  2 21    6     160   110   3.9   2.875 17.02 0     1     4     4    
#>  3 22.8  4     108   93    3.85  2.32  18.61 1     1     4     1    
#>  4 21.4  6     258   110   3.08  3.215 19.44 1     0     3     1    
#>  5 18.7  8     360   175   3.15  3.44  17.02 0     0     3     2    
#>  6 18.1  6     225   105   2.76  3.46  20.22 1     0     3     1    
#>  7 14.3  8     360   245   3.21  3.57  15.84 0     0     3     4    
#>  8 24.4  4     146.7 62    3.69  3.19  20    1     0     4     2    
#>  9 22.8  4     140.8 95    3.92  3.15  22.9  1     0     4     2    
#> 10 19.2  6     167.6 123   3.92  3.44  18.3  1     0     4     4    
#> # … with 22 more rows

Created on 2019-03-11 by the reprex package (v0.2.1)

3

If you have a list, you can do the following:

# Reprodução da lista

for (i in 1:6) {
  assign(paste('var', i, sep = '_'), 
         runif(30, 20, 100))
}
dataset <- cbind.data.frame(mget(ls(pattern = '*var')))
cluster <- kmeans(dataset, centers = 3)
dataset$kmeans <- as.factor(cluster[['cluster']])
mylist <- split(dataset, dataset$kmeans)
names(mylist) <- paste('datasets', seq_along(mylist), sep = '_')

mylist is the name of the list with three data.frames.

Now, convert every variable, every data.frame, in character:

library(tidyverse)

novo <- mylist %>% 
  map(~mutate_all(., as.character))

novo is the list of variables converted into each data.frame.

prove coercion with sapply:

sapply(novo, function(x) {
 sapply(x, class)
})

       datasets_1  datasets_2  datasets_3 
var_1  "character" "character" "character"
var_2  "character" "character" "character"
var_3  "character" "character" "character"
var_4  "character" "character" "character"
var_5  "character" "character" "character"
var_6  "character" "character" "character"
kmeans "character" "character" "character"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.