关于sapply/plyr语法的问题:如何将变量值传递给函数

Ada*_* SO 4 r function plyr

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

例如,而不是:ddply(bu,.(trial),function(x)print(x $ tangle))

有办法吗:ddply(bu,.(试用),print(纠结))

我问,因为有很多变量,这种符号变得非常麻烦.

谢谢!

G. *_*eck 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
Run Code Online (Sandbox Code Playgroud)


D.D*_*iso 5

只需在**ply命令中添加函数参数即可.例如:

ddply(my_data, c("var1","var2"), my_function, param1=something, param2=something)
Run Code Online (Sandbox Code Playgroud)

my_function通常是这样的

my_function(x, param1, param2)
Run Code Online (Sandbox Code Playgroud)

这是一个有效的例子:

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
Run Code Online (Sandbox Code Playgroud)