0

I am trying to subset my data but I was attempting to do it in a loop and then store those subsets into different dataframes. I have a dataframe named data with 20000 variables and I wanted to get sub-sets of that data.

One way of doing it would be for me to use: new_1000<-data[,1:1000]

new_5000<-data[,1:5000]

But I wanted to try looping. The attempt is below, where I was able to subset for the top 1000 new_1000. However, I do not know how I can go about to create another dataframe new_5000. Edits to this code are welcome.

new_1000<-list()
columns <-c(1:1000)
For (i in seq_along(columns)){
new[[i]] <-data[, columns[i]]
}
new_1000<-as.data.frame(new_1000)
thole
  • 117
  • 6

1 Answers1

0

This will give you a list of dataframes with the first n_cols columns:

new_dfs <- list()
for (n_cols in c(1000, 5000)) {
  new_dfs[[paste0("new_", n_cols)]] <- data[, seq(n_cols)]
}
zephryl
  • 14,633
  • 3
  • 11
  • 30