How to replicate a column within a data frame?

Viewed 55

I am trying to replicate a column of a data frame into the same or a new data frame. My data frame df only contains one column:

col
1
2
3
4
5

I hope to get something like this (another/same data frame, not a matrix):

col1 col2 col3 col4 col5
1    1    1    1    1
2    2    2    2    2
3    3    3    3    3
4    4    4    4    4
5    5    5    5    5

I tried to create a new data frame by using new_df <- rep(df[,c(1)],5), which I don't understand why it didn't work.

1 Answers

Just assign the column

df[paste0('col', 2:5)] <- df$col

-ouptut

> df
  col col2 col3 col4 col5
1   1    1    1    1    1
2   2    2    2    2    2
3   3    3    3    3    3
4   4    4    4    4    4
5   5    5    5    5    5

Or if we are using rep, the input can be a list or data.frame instead of a vector i.e. df[,1] coerces the data.frame column to a vector as by default drop = TRUE in data.frame. Instead (if there is only column, either rep(df, 5)) or if more than one column subset as df[1] (- returns a data.frame with one column) as input in rep. The output will be a list of vectors, which we convert to data.frame by wrapping with data.frame

data.frame(rep(df[1],5))

Or may also use replicate

as.data.frame(replicate(5, df$col))

data

df <- structure(list(col = 1:5), class = "data.frame", row.names = c(NA, 
-5L))
Related