有没有办法用运行速度更快的东西来替换R中的这个循环?
简而言之,我正在努力加快速度。这是我的慢代码:有没有办法用运行速度更快的东西来替换R中的这个循环?,r,loops,R,Loops,简而言之,我正在努力加快速度。这是我的慢代码: library(dplyr) tmp <- unique(kat$pnr) # Sort out the unique entries (ends up to about 572000) sex = c() for(i in tmp){ # For each unique pnr, look up the sex and append it to the new dataset temptable <- filter
library(dplyr)
tmp <- unique(kat$pnr) # Sort out the unique entries (ends up to about 572000)
sex = c()
for(i in tmp){ # For each unique pnr, look up the sex and append it to the new dataset
temptable <- filter(kat, pnr == i)
sex[i] <- temptable$sex
}
库(dplyr)
tmp来自具有过滤器的独特元素的=
将更慢,并且在循环中也是如此。相反,在这种情况下,如果我们想在“pnr”的每个唯一元素的“sex”列中找到一些描述性统计信息,则使用groupby
操作可能更合适
library(dplyr)
kat %>%
group_by(pnr) %>%
summarise(val = fn(sex))
使用数据可以进一步加快速度。表
library(data.table)
setDT(kat)[, .(val = fn(sex)), by = .(pnr)]
注意:不清楚“性别”列上要应用的函数
如果目的是创建一个性的列表
,那么
lst1 <- split(kat$sex, kat$pnr)
lst1 kat$sex[!重复(kat$pnr)]