将函数应用于数据框的所有元素 [英] 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屋!
查看全文