使用循环子集数据帧 [英] Subset dataframe using a loop

查看:44
本文介绍了使用循环子集数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数据框:

I have a data frame that looks like this:

index   ID   date              Amount
2       1001 2010-06-08         0
21      1001 2010-10-08        10
6       1002 2010-08-16        30
5       1002 2010-11-25        20
9       1003 2010-01-01         0
8       1003 2011-03-06        10
12      1004 2012-03-12        10
11      1004 2012-06-21        10
15      1005 2010-01-01        30
13      1005 2010-04-06        20

我想对这些数据进行子集处理,以便获得新的数据帧,每个ID对应一个像这样

I want to subset this data so that I have new data frames, one for each ID like this

index   ID   date              Amount
2       1001 2010-06-08         0
21      1001 2010-10-08        10

6       1002 2010-08-16        30
5       1002 2010-11-25        20

等等。

我不需要保存新的数据帧,但可以使用它来执行一些基本的计算言语。我也想在包含超过10000个ID的整个表上执行此操作,因此需要循环。我尝试了这个

I don't need to save the new data frames, but use it to perform some basic calculations. Also I want to do this on my entire table consisting of more than 10000 IDs and hence the need for a loop. I tried this

    temp <- data.frame(Numb=c(),Dt=c(),Amt=c())
for (i in seq_along(stNew$ID)){
   temp[i,] <- subset(stNew, stNew[i,]==stNew$ID[i])
}

但这没用。有任何建议吗?

But that didn't work. Any suggestions?

推荐答案

可能是这样的

    IDs<-unique(df$ID)
    for (i in 1:length(IDs)){ 
    temp <- df[df$ID==IDs[i],]
    #more things to do with temp
    }

这篇关于使用循环子集数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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