简体   繁体   English

R:更快的规模替代

[英]R: A faster alternative to scaleBy

I am using scaleBy from the doBy R package, to standardize a variable by a condition for each subject in my dataset. 我正在使用doBy R包中的scaleBy,以针对数据集中每个主题的条件标准化变量。 I have about 5137 participants in my data set, each with about 120 observations. 我的数据集中约有5137名参与者,每个参与者约有120个观察值。 On that dataset, scaleBy is very slow (close to 15 minutes). 在该数据集上,scaleBy非常慢(接近15分钟)。 Other functions (eg, summaryBy, melt, dcast) work much faster (no more than 20 seconds). 其他功能(例如,summaryBy,melt,dcast)的工作速度更快(不超过20秒)。 I wonder whether there are faster simple alternatives for the scaleBy. 我想知道scaleBy是否有更快的简单替代方法。

Here is a simulation code that you can run to mimic my dataset, in terms of number of participants, number of conditions within each participant (it is a repeated measures design), and number of observations for each condition for each participant: 这是一个模拟代码,可以用来模拟我的数据集,包括参与者数量,每个参与者内的条件数量(这是重复测量设计)以及每个参与者对每个条件的观察数量:

 nSubj <- 5137 valuesPerSubj <- 120 nobs <- nSubj*valuesPerSubj ttt <- data.frame(cond=rep(c('a','b','c','d'),nobs/4), rt=rnorm(nobs,mean=700,sd=150), subj=rep(seq(1:nSubj),valuesPerSubj)) start <- Sys.time() zt <- scaleBy(rt ~ subj+cond, data=ttt) end <- Sys.time() duration <- end-start duration 

The scaleBy in this code takes my computer 11.7 minutes (you can reduce nSubj in the code above for faster testing). 这段代码中的scaleBy花了我的计算机11.7分钟(您可以减少上面代码中的nSubj以便进行更快的测试)。 Any faster solutions? 有更快的解决方案吗?

I found a much faster code. 我发现了一个更快的代码。 I replaced the scaleBy line with these two lines: 我用以下两行替换了scaleBy行:

 gttt <- group_by(ttt,subj,cond) zt <- mutate(gttt,zrt=as.numeric(scale(rt))) 

This code took less than 4 seconds to run. 这段代码不到4秒钟即可运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM