Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a function to all the elements of a data frame

Tags:

dataframe

r

apply

I am trying to apply some transformations to all the elements in a dataframe.

When using the regular apply functions, I get a matrix back and not a dataframe. Is there a way to get a dataframe directly without adding as.data.frame to each line?

df = data.frame(a = LETTERS[1:5], b = LETTERS[6:10])

apply(df, 1, tolower) #Matrix
apply(df, 2, tolower) #Matrix
sapply(df, tolower)   #Matrix

as.data.frame(sapply(df, tolower)) # Can I avoid "as.data.frame"?
like image 981
Deena Avatar asked Oct 27 '16 07:10

Deena


2 Answers

We can use lapply and assign it back to 'df'

df[] <- lapply(df, tolower)

The [] preserves the same structure as the original dataset. Using apply convert it to a matrix and that is not recommended.

like image 118
akrun Avatar answered Sep 20 '22 04:09

akrun


Here's a way using dplyr:

library(dplyr)
df  %>% mutate_each(funs(tolower))
like image 20
Tim Goodman Avatar answered Sep 21 '22 04:09

Tim Goodman