将功能应用于数据框的所有元素 [英] Apply a function to all the elements of a data frame
本文介绍了将功能应用于数据框的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试对数据框中的所有元素进行一些转换.
I am trying to apply some transformations to all the elements in a dataframe.
使用常规套用函数时,我得到的是矩阵而不是数据框.有没有一种方法可以直接获取数据帧而无需在每行中添加as.data.frame
?
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"?
推荐答案
我们可以使用lapply
并将其分配回'df'
We can use lapply
and assign it back to 'df'
df[] <- lapply(df, tolower)
[]
保留与原始数据集相同的结构.使用apply
将其转换为matrix
,不建议这样做.
The []
preserves the same structure as the original dataset. Using apply
convert it to a matrix
and that is not recommended.
这篇关于将功能应用于数据框的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文