Martin Castellan
Martin Castellan

Reputation: 11

Fill dataframe column repeating row values in r

I am trying to fill a data frame column with a vector, need to repeat the vector values before passing to the next vector value like this. I work in R.

NEW_COLUMN=c(1,2)

Original data frame example

A B C    A B C NEW_COLUMN
X X X    X X X 1
X X X    X X X 1
X X X    X X X 2
X X X    X X X 2

Upvotes: 0

Views: 1090

Answers (1)

Geosopher
Geosopher

Reputation: 11

You could try it like this:

df <- data.frame(a = c(1,2,3,4),
             b = c(4,5,6,7),
             c = c(7,8,9,10))

newcol <- c(1,2)

#instert new column by repeating each element in vector "newcol" 2 times
df2 <- dplyr::mutate(df, d = rep(newcol, each = 2))

df2

Upvotes: 1

Related Questions