Apply to each column in multiple dataframes

Viewed 58

If I were to find the class of each column I would normally (assuming I'd like to avoid str):

lapply(df, class)

However, what if I wanted to do the same for multiple dataframes? E.g.:

x <- data.table(col_1 = c('a', 'b')
                , col_2 = 1:2
                ); x

y <- data.table(col_3 = 3:4
                , col_4 = c('c', 'd')
                ); y

My attempt is:

lapply(1:2, function(i) class( list(x,y)[[i]] ) )

but it gives:

[[1]]
[1] "data.table" "data.frame"

[[2]]
[1] "data.table" "data.frame"

i.e. R is failing to apply to the columns inside each element (in this case, each dataframe) of the list. If I am after an apply solution (especially not a For loop or str), what would that be? Or would Reduce, Map or do.call achieve this too? Thank you.

4 Answers

Put the datatables in a list and then use lapply to iterate over them.

lapply(list(x, y), function(x) sapply(x, class))

#[[1]]
#      col_1       col_2 
#"character"   "integer" 

#[[2]]
#      col_3       col_4 
#  "integer" "character" 

As x and y inherit from lists, they can be concatenated, so you can use

lapply(c(x,y), class)
# $col_1
# [1] "character"
# 
# $col_2
# [1] "integer"
# 
# $col_3
# [1] "integer"
# 
# $col_4
# [1] "character"

We may use

library(purrr)
map(c(x, y), class)
$col_1
[1] "character"

$col_2
[1] "integer"

$col_3
[1] "integer"

$col_4
[1] "character"

We could use base R Map:

Map(class,c(x,y))
$col_1
[1] "character"

$col_2
[1] "integer"

$col_3
[1] "integer"

$col_4
[1] "character"
Related