Get value based on another column in dplyr

I have the following dataset:

df <- mtcars[1:4,c("wt","qsec")]
df

                  wt  qsec
Mazda RX4      2.620 16.46
Mazda RX4 Wag  2.875 17.02
Datsun 710     2.320 18.61
Hornet 4 Drive 3.215 19.44

How to achieve the following by using dynamic variable via dplyr?

df %>% 
  mutate(wt=floor(wt[which.min(qsec)]))

This is what I tried so far:

myvar<-"wt"

df %>% 
  mutate(!!myvar :=floor(!!as.name(myvar)[which.min(qsec)]))

Error in which.min(qsec) : object 'qsec' not found

Please let me know if you know why does the above code failed. Thank you!

>Solution :

In the latest versions of dplyr, you use := to set names with a character value and you use .data[[]] to get columns with a character value. Your transformation would look like this

df %>% mutate("{myvar}" := floor(.data[[myvar]][which.min(qsec)]))

Leave a Reply