Search code examples
rdataframerbind

Append same values to multiple columns of a data.frame


I have a short vector of values:

five_values <- (c("17", "93", "119", "399", "439"))

and a dataframe:

df <- data.frame("Col1" = sample(1:100, 10), "Col2" = sample(1:100, 10), "Col3" = sample(1:100, 10))

I want to append the same five values to the end of each column of the data frame. So the last five rows of all columns should have exactly the same five values. If I use rbind() like this:

rbind(df, c("17", "93", "119", "399", "439"))

it appears to attempt to add the first value to Col1, the second to Col2 etc, rather than adding the full set of five to Col1, then to Col2. So I get an error message because the number of values is not a multiple of the number of columns.

I tried to use a for loop:

for(i in 1:3) {
  output = c("17", "93", "119", "399", "439")
  rbind(df[,1:3], output)
}

But got the same result.

Can anyone help?


Solution

  • In R data.frame has its own rbind() implementation which you can read about in its dedicated help page: help(rbind.data.frame). In short - it allows you to bind two data.frames if they have the same number of columns and their column names are the same.

    So one way would be to create a second data.frame for binding:

    df2 <- data.frame(Col1 = five_values, Col2 = five_values, Col3 = five_values)
    rbind(df, df2)
    

    Under the hood, in R, the data.frame is a list. And the rbind method also allows us to bind a list to the data.frame. In this case the list has to have as many elements as there are columns in the data.frame, and all the list elements must be of equal length. So this also works:

    rbind(df, rep(list(five_values), ncol(df)))