我试图在数据集中的多个单独主题上运行glm以返回特定系数。我在这里找到了一个很好的例子(Multiple glm in for loop)。除此之外,结果将打印到屏幕上,但之后无法使用。因此,我无法保存结果或重命名变量,除非我在RStudio中突出显示屏幕然后复制/粘贴到Excel中。
数据:
Subject SNRs Prop_Correct Ntrials
1 3 0.65 100
1 0 0.40 100
1 -3 0.15 100
1 -6 0.00 100
1 -9 0.00 100
1 -12 0.00 100
2 3 0.65 100
2 0 0.40 100
2 -3 0.15 100
2 -6 0.00 100
2 -9 0.00 100
2 -12 0.00 100
3 3 0.65 100
3 0 0.40 100
3 -3 0.15 100
3 -6 0.00 100
3 -9 0.00 100
3 -12 0.00 100
我的剧本:
ddply(Data, .(Subject), function (x){
intercept <- coef(summary(glm(Prop_Correct~SNRs, weights=Ntrials,family=quasibinomial(link='logit'),data=x)))[1]
slope <- coef(summary(glm(Prop_Correct~SNRs, weights=Ntrials,family=quasibinomial(link='logit'),data=x)))[2]
SNR50 <- (log(0.5/(1-0.5))/slope) - (intercept/slope)
Data_Summary <- c(SNR50,slope)
})
这给了我这个输出:
Subject V1 V2
1 1 1.266165 0.4834356
2 2 1.266165 0.4834356
3 3 1.266165 0.4834356
然而:
Data_Summary
Error: object 'Data_Summary' not found
如何将ddply函数的结果提供给主/全局环境?
答案 0 :(得分:0)
将结果分配给变量:
library(tidyr)
mydf <- data.frame(X = c('a', NA, NA, 'b', NA, NA, 'c'), Y =rep(1,7))
mydf %>% fill(X)
X Y
1 a 1
2 a 1
3 a 1
4 b 1
5 b 1
6 b 1
7 c 1
虽然有很多事情要发生,但是如同没有分配给变量那样对待它,它只输出结果,如果你想保留结果,你将它分配给变量,例如< / p>
Data_Summary_df <- ddply(Data, .(Subject), function (x){
intercept <- coef(summary(glm(Prop_Correct~SNRs, weights=Ntrials,family=quasibinomial(link='logit'),data=x)))[1]
slope <- coef(summary(glm(Prop_Correct~SNRs, weights=Ntrials,family=quasibinomial(link='logit'),data=x)))[2]
SNR50 <- (log(0.5/(1-0.5))/slope) - (intercept/slope)
Data_Summary <- c(SNR50,slope)
})
Data_Summary_df