[英]R: Applying function to DataFrame
I have following code: 我有以下代码:
library(Ecdat)
data(Fair)
Fair[1:5,]
x1 = function(x){
mu = mean(x)
l1 = list(s1=table(x),std=sd(x))
return(list(l1,mu))
}
mylist <- as.list(Fair$occupation,
Fair$education)
x1(mylist)
What I wanted is that x1 outputs the result for the items selected in mylist. 我想要的是x1输出mylist中所选项目的结果。 However, I get In mean.default(x) : argument is not numeric or logical: returning NA
. 但是,我得到了In mean.default(x) : argument is not numeric or logical: returning NA
。
You need to use lapply if your passing a list to a function 如果将列表传递给函数,则需要使用lapply
output<-lapply(mylist,FUN=x1)
This will process your function x1 for each element in mylist and return a list of results to output. 这将为mylist中的每个元素处理函数x1并返回结果列表以输出。
Here the mylist
is created not in the correct way and a list
is not needed also as data.frame
is a list
with columns of equal length. 在这里, mylist
以正确的方式不是创建一个list
不需要也可以作为data.frame
是一个list
长度相等的列。 So, just subset the columns of interest and apply the function 因此,只需对感兴趣的列进行子集化并应用功能
lapply(Fair[c("occupation", "education")], x1)
In the OP's code, as.list
simply creates a list
of length
601 with only a single element in each. 在OP的代码中, as.list
仅创建length
601的list
,每个list
中只有一个元素。
str(mylist)
#List of 601
#$ : int 7
#$ : int 6
#$ : int 1
#...
#...
Another problem in the code is that it is not even considering the 2nd argument. 代码中的另一个问题是它甚至没有考虑第二个参数。 Using a simple example 用一个简单的例子
as.list(1:3, 1:2)
#[[1]]
#[1] 1
#[[2]]
#[1] 2
#[[3]]
#[1] 3
The second argument is not at all considered. 完全没有考虑第二个参数。 It could have been 可能是
list(1:3, 1:2)
#[[1]]
#[1] 1 2 3
#[[2]]
#[1] 1 2
But for data.frame columns, we don't need to explicitly call the list
as it is a list
of vectors
that have equal length. 但是对于data.frame列,我们不需要显式调用该list
因为它是长度相等的vectors
的list
。
Regarding the error in OP's post, mean
works on vector
s and not on list
or data.frame
. 关于OP帖子中的错误, mean
适用于vector
,而不适用于list
或data.frame
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.