4

有没有办法将 ddply/sapply 中的变量值直接传递给没有函数 (x) 表示法的函数?

例如代替: ddply(bu,.(trial), function (x) print(x$tangle) )

有没有办法: ddply(bu,.(trial), print(tangle) )

我问是因为有很多变量,这个符号变得非常麻烦。

谢谢!

4

2 回答 2

7

您可以fn$gsubfn包中使用。只需在有问题的函数前面加上fn$,然后您就可以使用如下所示的公式表示法:

> library(gsubfn)
>
> # instead of specifying function(x) mean(x) / sd(x)
>
> fn$sapply(iris[-5], ~ mean(x) / sd(x))
Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
    7.056602     7.014384     2.128819     1.573438 

> library(plyr)
> # instead of specifying function(x) colMeans(x[-5]) / sd(x[-5])
> 
> fn$ddply(iris, .(Species), ~ colMeans(x[-5]) / sd(x[-5]))
     Species Sepal.Length Sepal.Width Petal.Length Petal.Width
1     setosa     14.20183    9.043319     8.418556    2.334285
2 versicolor     11.50006    8.827326     9.065547    6.705345
3  virginica     10.36045    9.221802    10.059890    7.376660
于 2011-01-26T20:52:57.600 回答
5

只需在 **ply 命令中添加您的函数参数。例如:

ddply(my_data, c("var1","var2"), my_function, param1=something, param2=something)

my_function 通常看起来像

my_function(x, param1, param2)

这是一个工作示例:

require(plyr)

n=1000
my_data = data.frame(
    subject=1:n, 
    city=sample(1:4, n, T), 
    gender=sample(1:2, n, T), 
    income=sample(50:200, n, T)
    )


my_function = function(data_in, dv, extra=F){
    dv = data_in[,dv]
    output = data.frame(mean=mean(dv), sd=sd(dv))
    if(extra) output = cbind(output,  data.frame(n=length(dv), se=sd(dv)/sqrt(length(dv)) )  )
    return(output)
}

#with params
ddply(my_data, c("city", "gender"), my_function, dv="income", extra=T)

  city gender     mean       sd   n       se
1    1      1 127.1158 44.64347  95 4.580324
2    1      2 125.0154 44.83492 130 3.932283
3    2      1 130.3178 41.00359 107 3.963967
4    2      2 128.1608 43.33454 143 3.623816
5    3      1 121.1419 45.02290 148 3.700859
6    3      2 120.1220 45.01031 123 4.058443
7    4      1 126.6769 38.33233 130 3.361968
8    4      2 125.6129 44.46168 124 3.992777

#without params
ddply(my_data, c("city", "gender"), my_function, dv="income", extra=F)

  city gender     mean       sd
1    1      1 127.1158 44.64347
2    1      2 125.0154 44.83492
3    2      1 130.3178 41.00359
4    2      2 128.1608 43.33454
5    3      1 121.1419 45.02290
6    3      2 120.1220 45.01031
7    4      1 126.6769 38.33233
8    4      2 125.6129 44.46168
于 2012-06-05T23:49:27.920 回答