0

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.

El Hocko
  • 2,581
  • 1
  • 13
  • 22

3 Answers3

1

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
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
  • what's the difference between `mtcars[,names(tmp)] <- tmp` and `mtcars[names(tmp)] <-tmp`? I don't see any. – El Hocko Nov 09 '22 at 22:41
1

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)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • `mtcars <- tmp` will produce a table with only two columns, instead, the OP wants to update `mtcars` with those values in `tmp` – Jilber Urbina Nov 09 '22 at 17:32
1

answer is:

mtcars <- mutate(mtcars, tmp)

edit: add this solution, which could be more intuitive

newdf <- mtcars |> mutate(tmp)

El Hocko
  • 2,581
  • 1
  • 13
  • 22