R循环优化/循环太费时了 [英] R Loop optimisation/ Loop is way too time consuming

查看:152
本文介绍了R循环优化/循环太费时了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下循环需要老化。有什么办法,以更有时间效率的方式吗?以下data.table由27个变量和超过600k个观察值组成。

The following loop takes ages. Is there any way to this in a more time-efficient way? The following data.table consists of 27 variables and more than 600k observations.

data <- read.table("file.txt", header = T, sep= "|")
colnames(data)[c(1)] <- c("X")
data <- as.data.table(data)
n=1;
vector <- vector()
for(i in 2:nrow(data))
{
  if(data[["X"]][i] != data[["X"]][i-1])
  {
   n=1; vector[i]=1} 
 else {
   n=n+1; vector[i]=n}}

基本上,我需要索引每个外观的唯一条目X,即第一次出现,第二次出现,等等,然后合并到现有数据作为附加列。然而,我在编译向量的时候有股票。

Basically, I need to index every appearance of a unique entry in X, i.e. the first time it appeared, the second time it appeared, etc and then merge this to the existing data as additional column. However, I got stock at compiling the vector.

谢谢。

推荐答案

首先,使用 fread

DT <- fread("file.txt", sep = "|")

接下来,使用 setnames

setnames(DT, 1, "X")

code> rowid :

Finally, use rowid:

DT[ , vector := rowid(X)]    

这篇关于R循环优化/循环太费时了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆