Append same values to multiple columns

Hi all. I feel like this should be simple but I can't figure it out. 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 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 etc. as I want. So I get an error message because the number of values is not a multiple of the number of columns.

I tried a for loop, something like this:

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?

One way to do this (if I understand you correctly) would be to transform the vector into a matrix like:

set.seed(2023)
five_values <- (c(17, 93, 119, 399, 439))

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

five_mat <- matrix(five_values,
                   nrow=5,
                   ncol=3,
                   byrow=F,
                   dimnames=list(NULL,
                                 c("Col1","Col2","Col3")))

rbind(df, five_mat)
#>    Col1 Col2 Col3
#> 1    80   72   57
#> 2    47   63   98
#> 3    72   98   38
#> 4    26    3   85
#> 5    44   79   41
#> 6    65   45   30
#> 7    29    4   39
#> 8    49    5   49
#> 9    81   24   44
#> 10    5    9   48
#> 11   17   17   17
#> 12   93   93   93
#> 13  119  119  119
#> 14  399  399  399
#> 15  439  439  439
Created on 2023-04-07 with reprex v2.0.2

@HanOostdijk , that was my thought, but it looks that he wants the five_num vector in each column, and, what's more, the elements are character strings, not numeric. So, to preserve the numeric typeof for the values of df, each column would have to hold a list object. Then the vector of lists can be extended with another list even if it contains typeof character.

Without knowing the use case for such an odd data structure, I don't want to get further, in case it's headed toward a presentation table.

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.