通过数据帧循环子集

时间:2019-12-10 17:57:46

标签: r loops subset

我有20个数据帧,我想将4个变量子集到一个新的数据帧中。

DF1 <- subset(Circle1.csv, select = c(col1, col2, col3, col4))
DF2 <- subset(Circle2.csv, select = c(col1, col2, col3, col4))

我不想写20次;有办法循环吗?

非常感谢

2 个答案:

答案 0 :(得分:0)

将所有对象放入list,然后通过遍历subset

使其list一次
lst1 <- lapply(mget(sprintf("Circle%d.csv", 1:20)), subset, 
            select = c(col1, col2, col3, col4))

或与dplyr/purrr

library(purrr)
library(dplyr)
lst1 <- map(mget(sprintf("Circle%d.csv", 1:20)), ~ .x %>% 
                      select(col1:col4))

答案 1 :(得分:0)

使用for循环

nrows <- 1:4 # number of rows to subset
colNames <- c('col1', 'col2', 'col3', 'col4') # column names

# assign subset of dataframe
for (i in 1:20) {
  assign(x = paste0('DF', i), value = get(paste0('Circle', i, '.csv'))[nrows, colNames])
}