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

multiple many columns by specific column using lists

I am basically working off of this answer, but want to add one more wrinkle I can’t figure out. I want to multiple all columns contained in a list by the weight column, similar to the example below:

#df 1
Id = c("1", "2", "3", "4")
Persons = c(300, 400, 200, 5000)
Houses = c(20, 40, 10, 23)
Ages =  c(45, 34, 50, 44)
Races = c(1, 3, 1, 2)
weight = c(0.9, 1.2, 0.8, 1.1)

estimates = data.frame(Id, Persons, Houses, Ages, Races, weight)
list <- as.list(colnames(subset(estimates, select = -c(Id, weight))))
estimates <- estimates %>% mutate_each(funs(.*weight), . %in% list)

But I keep getting the following error:

Error in as_indices_impl(): ! Must subset columns with a valid
subscript vector. ✖ Subscript has the wrong type logical. ℹ It must
be numeric or character.

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

>Solution :

Using the modern across() instead of the deprecated mutate_each():

estimates %>% mutate(across(all_of(unlist(list)), \(x) x * weight))

Or with base R:

estimates[unlist(list)] <- estimates[unlist(list)] * estimate$weight

Of course, if you simplify your definition keeping it a character vector, then you can use cols instead of unlist(list).

cols = setdiff(names(estimtes), c("Id", "weight"))

Or, with across() you can skip the list definition entirely:

estimates %>% mutate(across(!c(Id, weight), \(x) x * weight))
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