Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading