Apply a function to all the elements of a data frame

给你一囗甜甜゛ 提交于 2019-12-20 09:38:01

问题


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"?

回答1:


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.




回答2:


Here's a way using dplyr:

library(dplyr)
df  %>% mutate_each(funs(tolower))


来源:https://stackoverflow.com/questions/40278906/apply-a-function-to-all-the-elements-of-a-data-frame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!