subset data frame in R using loop

不打扰是莪最后的温柔 提交于 2019-11-30 10:09:35

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
    }
OB83

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

    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]])
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!