Q:

vector to dataframe in r given length of vector

I have vectors of different lengths.  For instance:
df1
[1]   1  95   5   2 135   4   3 135   4   4 135   4   5 135   4   6 135   4

df2
[1]   1  70   3   2 110   4   3 112   4

I'm trying to write a script in R in order to have any vector enter the function or for loop and it returns a dataframe of three columns.  So a separate dataframe for each input vector.  Each vector is a multiple of three (hence, the three columns).  I'm fairly new to R in terms of writing functions and can't seem to figure this out.  Here was my attempt:
newdf = c()
ld <- length(df1)
ld_mult <- length(df1)/3
ld_seq <- seq(from=1,to=ld,by=3)
ld_seq2 < ld_seq +2
for (i in 1:ld_mult) {
  newdf[i,] <- df1[ld_seq[i]:ld_seq2[i]]
}

the output I want for df1 would be:
1 95    5
2 135   4
3 135   4
4 135   4
5 135   4
6 135   4

A:

Here's an example of how you could use matrix for that purpose:
x <- c(1, 95, 5,2, 135, 4, 3, 135, 4)

as.data.frame(matrix(x, ncol = 3, byrow = TRUE))
#  V1  V2 V3
#1  1  95  5
#2  2 135  4
#3  3 135  4

And 
y <- c(1, 70, 3, 2, 110, 4, 3, 112, 4)
as.data.frame(matrix(y, ncol = 3, byrow = TRUE))
#  V1  V2 V3
#1  1  70  3
#2  2 110  4
#3  3 112  4

Or if you want to make it a custom function:
newdf <- function(vec) {
  as.data.frame(matrix(vec, ncol = 3, byrow = TRUE))
}

newdf(y)
#V1  V2 V3
#1  1  70  3
#2  2 110  4
#3  3 112  4

You could also let the user specify the number of columns he wants to create with the function if you add another argument to newdf:
newdf <- function(vec, cols = 3) {
  as.data.frame(matrix(vec, ncol = cols, byrow = T))
}

Now, the default number of columns is 3, if the user doesnt specify a number. If he wants to, he could use it like this:
newdf(z, 5) # to create 5 columns

Another nice little addon for the function would be a check if the input vector length is a multiple of the number of columns specified in the function call:
newdf <- function(vec, cols = 3) {
  if(length(vec) %% cols != 0) {
    stop("Number of columns is not a multiple of input vector length. Please double check.")
  }
  as.data.frame(matrix(vec, ncol = cols, byrow = T))
}

newdf(x, 4)
#Error in newdf(x, 4) : 
#  Number of columns is not a multiple of input vector length. Please double check.

If you had multiple vectors sitting in a list, here's how you could convert each of them to be a data.frame:
> l <- list(x,y)
> l
#[[1]]
#[1]   1  95   5   2 135   4   3 135   4
#
#[[2]]
#[1]   1  70   3   2 110   4   3 112   4

> lapply(l, newdf)
#[[1]]
#  V1  V2 V3
#1  1  70  3
#2  2 110  4
#3  3 112  4
#
#[[2]]
#  V1  V2 V3
#1  1  70  3
#2  2 110  4
#3  3 112  4

