简体   繁体   中英

How to separate a vector every fifth element?

i have a vector

a<-as.vector(diag(5))

How to separate this vector every 5 numbers and create a data.frame by joining each in a row? my idea is to do this https://imgur.com/X7JLMYH one column, each row of that column as if it were diag (5). Each line will identify a different object, so you need to follow the image order. length must equal number of numbers within each line

We can use matrix (as the length is already a multiple of 5) and then wrap with as.data.frame

as.data.frame(matrix(a, ncol = 5, byrow = TRUE))

If we want as a single column of strings, can paste each row to create that single column data

data.frame(col1 = do.call(paste, as.data.frame(matrix(a, ncol = 5, 
       byrow = TRUE))))

Or place it as a list column

data.frame(col1 = I(asplit(matrix(a, ncol = 5, byrow = TRUE), 1)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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