-1

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://i.stack.imgur.com/LeOBh.jpg 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

  • Can you include what you're trying to get? Right now it's unclear – camille Dec 27 '19 at 18:46
  • I am trying to turn a matrix into a data.frame https://stackoverflow.com/questions/59491515/how-to-turn-a-binary-matrix-into-a-data-frame-in-r-lpsolveapi?noredirect=1#comment105179352_59491515 – Vinicius Soares Dec 27 '19 at 18:49
  • I don't get how these two are related. You can [edit] this post with the expected output – camille Dec 27 '19 at 18:56
  • Also, seems like this should be covered by https://stackoverflow.com/q/32173557/5325862 – camille Dec 27 '19 at 19:04
  • I don't want to have to type this matrix all the time got it? I am trying to think of a way to make each line of this matrix become a row of a data.frame, so I thought of turning this diag (5) into a vector with as.vector and after that cutting the vector every "n" elements and create a vector of each element and then with the created vectors create a data.frame. – Vinicius Soares Dec 27 '19 at 19:06

1 Answers1

2

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)))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/204972/discussion-on-answer-by-akrun-how-to-separate-a-vector-every-fifth-element). – Samuel Liew Dec 28 '19 at 00:14