pdx
pdx

Reputation: 301

R - split list every x items

I have data to analyse that is presented in the form of a list (just one row and MANY columns).

A B C D E F G H I
1 2 3 4 5 6 7 8 9 

Is there a way to tell R to split this list every x items and get something as seen below (the columns C D E F G H I are virtually the same as A B)?

A B
1 2
3 4
5 6
7 8
9

Upvotes: 1

Views: 659

Answers (1)

akrun
akrun

Reputation: 887991

If the number of columns is a multiple of 'x', then we unlist the dataset, and use matrix to create the expected output.

as.data.frame(matrix(unlist(df1), ncol=2, dimnames=list(NULL, c("A", "B")) , byrow=TRUE))

If the number of columns is not a multiple of 'x', then

x <- 2
gr <- as.numeric(gl(ncol(df1), x, ncol(df1)))
lst <- split(unlist(df1), gr)
do.call(rbind, lapply(lst, `length<-`, max(lengths(lst))))
#   A  B
# 1 1  2
# 2 3  4
# 3 5  6
# 4 7  8
# 5 9 NA

Upvotes: 2

Related Questions