简体   繁体   English

通过数据帧循环子集

[英]loop subset through data frames

i have 20 data frames of which i would like to subset 4 variables into a new data frame.我有 20 个数据帧,我想将其中的 4 个变量子集到一个新的数据帧中。

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

I don't want to write this out 20 times;我不想把这个写出 20 次; is there a way of looping this ?有没有办法循环这个?

many thanks非常感谢

Get all the objects into a list , and subset it once by looping over the list将所有对象放入一个list ,并通过循环遍历该list对其进行一次subset

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

Or with dplyr/purrr或者使用dplyr/purrr

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

using for loop使用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])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM