Looping across 10 columns at a time in R

2019-05-27 11:42发布

问题:

I have a dataframe with 1000 columns. I am trying to loop over 10 columns at a time and use the seqdef() function from the TraMineR package to do sequence alignment across the data in those columns. Hence, I want to apply this function to columns 1-10 in the first go-around, and columns 11-20 in the second go-around, all the way up to 1000.

This is the code I am using.

library(TraMineR)
by(df[, 1:10], seqdef(df))

However, this only loops over the first 10 and then stops. How do I loop it across chunks of 10 columns?

回答1:

You could do something like this using mapply and setting the sequence of columns to loop across.

colpicks <- seq(10,1000,by=10)
mapply(function(start,stop) seqdef(df[,start:stop]), colpicks-9, colpicks)