Subset dataframe using a loop

前端 未结 3 1780
野性不改
野性不改 2020-12-29 15:55

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       10         


        
相关标签:
3条回答
  • 2020-12-29 16:19

    Take a look at the list2env and split function. Hereby some examples using the iris dataset.

    Two way:

    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
    

    One way:

    list2env(split(iris, iris$Species), envir = .GlobalEnv)
    

    Or you can assign custom names for the new datasets with a for loop:

    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]])
    }
    

    Updates with examples

    Related post

    0 讨论(0)
  • 2020-12-29 16:28
        iris_split <- split(iris, iris$Species)
    

    Dynamically you can assign the data.frame name

        new_names <- as.character(unique(iris$Species))
    
        for (i in 1:length(iris_split)) {
        assign(new_names[i], iris_split[[i]])
        }
    
    0 讨论(0)
  • 2020-12-29 16:32

    may be like this

        IDs<-unique(df$ID)
        for (i in 1:length(IDs)){ 
        temp <- df[df$ID==IDs[i],]
        #more things to do with temp
        }
    
    0 讨论(0)
提交回复
热议问题