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

tidyverse mutate with an external vector whose elements are column values in a data frame

Let’s assume the following vector:

prices <- c(10, 15, 20, 30)

and the following data frame:

df <- data.frame(count = c(1, 3, 2, 4))

What I want to do is, depending on the count value in df, taking the 1:count values from the prices vector and sum these up in my data frame.

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

So I thought I could do:

library(tidyverse)
df |>
  mutate(sum = sum(!!prices[1:count]))

However, this gives an error:

Error in quos(..., .ignore_empty = "all") : 
  object 'count' not found

I guess it’s because it looking into the external vector and then searching for count in the global environment, however, it only exists in df.

So question is how can I feed in this external vector into my data frame an reference its elements by the count values?

Expected output would be:

  count sum
1     1  10
2     3  45
3     2  25
4     4  75

>Solution :

With sapply. And use .GlobalEnv$ if necessary:

df |>
  mutate(sum = sapply(count, \(x) sum(.GlobalEnv$prices[1:x])))

#   count sum
# 1     1  10
# 2     3  45
# 3     2  25
# 4     4  75
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