R中的子集数据帧使用循环

Bal*_*nde 4 r subset dataframe

我有一个如下所示的数据框:

----------

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
Run Code Online (Sandbox Code Playgroud)

我希望对这些数据进行子集化,以便我有新的数据帧,每个ID就像这样

index   ID   date              Amount
2       1001 2010-06-08         0
21      1001 2010-10-08        10
Run Code Online (Sandbox Code Playgroud)

和

6       1002 2010-08-16        30
5       1002 2010-11-25        20
Run Code Online (Sandbox Code Playgroud)

等等.

我不需要保存新的数据帧,但用它来执行一些基本的计算.此外,我想在我的整个表上执行此操作,该表包含超过10000个ID,因此需要循环.我试过这个

    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])
}
Run Code Online (Sandbox Code Playgroud)

但那没用.有什么建议?谢谢.

OB8*_*B83 10

看看list2env和split函数。以下是一些使用 iris 数据集的示例。

两种方式:

list_df <- split(iris, iris$Species) #split the dataset into a list of datasets based on the value of iris$Species
list2env(list_DF, envir= .GlobalEnv) #split the list into separate datasets
Run Code Online (Sandbox Code Playgroud)

单程:

list2env(split(iris, iris$Species), envir = .GlobalEnv)
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用for循环为新数据集分配自定义名称:

iris_split <- split(iris, iris$Species)
new_names <- c("one", "two", "three")
for (i in 1:length(iris_split)) {
  assign(new_names[i], iris_split[[i]])
}
Run Code Online (Sandbox Code Playgroud)

示例更新

相关帖子


Ana*_*nta 6

可能是这样的

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


小智 6

    iris_split <- split(iris, iris$Species)
Run Code Online (Sandbox Code Playgroud)

您可以动态分配 data.frame 名称

    new_names <- as.character(unique(iris$Species))

    for (i in 1:length(iris_split)) {
    assign(new_names[i], iris_split[[i]])
    }
Run Code Online (Sandbox Code Playgroud)