Dre
Dre

Reputation: 723

How to replace values in multiple columns in a data.frame with values from a vector in R?

I would like to replace the values in the last three columns in my data.frame with the three values in a vector.

Example of data.frame

df
A  B  C  D
5  3  8  9

Vector

1  2  3

what I would like the data.frame to look like.

df
A  B  C  D
5  1  2  3

Currently I am doing:

df$B <- Vector[1]
df$C <- Vector[2]
df$D <- Vector[3]

I would like to not replace the values one by one. I would like to do it all at once.

Any help will be appreciated. Please let me know if any further information is needed.

Upvotes: 1

Views: 381

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269644

Try this:

df[-1] <- 1:3

giving:

> df
  A B C D
1 5 1 2 3

Alternately, we could do it non-destructively like this:

replace(df, -1, 1:3)

Note: The input df in reproducible form is:

df <- data.frame(A = 5, B =3, C = 8, D = 9)

Upvotes: 2

akrun
akrun

Reputation: 887128

We can subset the last three columns of the dataset with tail, replicate the 'Vector' to make the lengths similar and assign the values to those columns

df[,tail(names(df),3)] <- Vector[col(df[,tail(names(df),3)])]
df
#  A B C D
#1 5 1 2 3

NOTE: I replicated the 'Vector' assuming that there will be more rows in the 'df' in the original dataset.

Upvotes: 2

Related Questions