R edit subset of data frame and override original row-values

134 views Asked by At

I have a dataframe, where I extract a certain subset:

tmp <- mtcars |> select(disp, hp)

then I make some data manipulation

tmp$disp <- tmp$disp*0
tmp$hp <- tmp$hp*2

Now I want to reintegrate the changes into the original How?

Of course I could work on the original df in the first place but I just want to know how to replace all values from a df by a subset.

I want to keep the order of the column names and if possible I don't want to use any index. I also assume there are use cases where the select query is long.

3

There are 3 answers

0
El Hocko On BEST ANSWER

answer is:

mtcars <- mutate(mtcars, tmp)

edit: add this solution, which could be more intuitive

newdf <- mtcars |> mutate(tmp)

1
Jilber Urbina On

You need to select names in mtcars that match with names in tmp and then replace values.

mtcars[,names(tmp)] <- tmp
head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6    0 220 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6    0 220 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4    0 186 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6    0 220 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8    0 350 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6    0 210 2.76 3.460 20.22  1  0    3    1
1
akrun On

Or instead of creating 'tmp',

library(dplyr)
mtcars <- mtcars %>%
     mutate(disp = disp*0, hp = hp*2)

Or in `data.table)

setDT(mtcars)[, c("disp", "hp) := .(0, hp *2)]

Or in base R

mtcars[c("disp", "hp")] <-  list(0, mtcars$hp*2)