Apply a function to all elements of a data frame

I am trying to apply some transformations to all elements in a data frame.

When using regular application functions, I return a matrix, not a frame. Is there a way to directly get the data file 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"? 
+5
source share
2 answers

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

 df[] <- lapply(df, tolower) 

[] retains the same structure as the original dataset. Using apply , convert it to matrix , and this is not recommended.

+11
source

The dplyr method is used dplyr :

 library(dplyr) df %>% mutate_each(funs(tolower)) 
+3
source

Source: https://habr.com/ru/post/1258875/


All Articles