TheWalküre
TheWalküre

Reputation: 45

Loops for commands in R?

I have a set of commands creating new data frames for a large number of subsets. The command is the same but the only thing that changes are some numbers of the subsets (from 1 to n).

The commands are:

a1 <- data[block$block.1$main.inds,]
a2 <- data[block$block.2$main.inds,]
a3 <- data[block$block.3$main.inds,]
.
.
.
a50 <- data[block$block.50$main.inds,]

I've tried to automatize this by using the following code but without success:

for (i in 1:50) {
        a[i]<- data[block$block.[i]$main.inds,]
}

Any help would be appreciated!

Upvotes: 1

Views: 29

Answers (1)

akrun
akrun

Reputation: 887048

It is better not to create multiple objects in the global env. In the present situation, we can use assign

for(i in 1:50) {
    assign(paste0('a', i), data[block[[paste0('block.', i)]]]$main.inds,])
 }

Or better to store it in a list

lst1 <- lapply(paste0('block.', 1:50), function(bl) data[block[[bl]]]$main.inds,])
names(lst1) <- paste0("a", 1:50)

Upvotes: 1

Related Questions