Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有办法用运行速度更快的东西来替换R中的这个循环?_R_Loops - Fatal编程技术网

有没有办法用运行速度更快的东西来替换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)]