0

I have a dataframe like this:

df <- data.frame(
  Group = c('A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'),
  Value = c(12, 88, 54, 76, 23, 44, 60, 52, 18)
)

I want to scale each group to a median of 100 and replace the Value column with the new value so the dataframe looks like this:

df_desired <- data.frame(
  Group = c('A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'),
  Value = c(20, 169.23, 122.73, 126.67, 44.23, 100, 100, 100, 40.91)
)

Using a scale_helper like this:

scale_helper <- function(x, value) x * value / median(x)

I could do this with a for loop, but I want to use purrr instead, if possible. Is there a straightforward way to do it using purrr, or is a for loop the better way to go here?

5
  • 1
    You don't explain why you want to do this with purrr. Commented Nov 13, 2021 at 17:07
  • Do I need to explain that? I’d like an alternative to a for loop. Commented Nov 13, 2021 at 17:11
  • Are you looking for df %>% group_by(Group) %>% mutate(new_val = scale_helper(Value, 100))? I don't see any neccessarity to use purrr here... Commented Nov 13, 2021 at 17:14
  • 1
    I'd choose purrr, if you are handling multiple data.frames stored in a list. For handling a single data.frame, dplyr should be sufficient. Commented Nov 13, 2021 at 17:15
  • @NatashaR, you are asking whether a for loop is better, but it's not clear to me how to measure that without knowing why you don't want to use one. Commented Nov 13, 2021 at 17:19

1 Answer 1

2

Loop for is not good way, but I don't understand why you want to use purr. I think, this is good version:

df %>% group_by(Group) %>% mutate(Value = scale_helper(Value, 100)) %>% as.data.frame()

Or you can use data.table. Something like this:

as.data.table(df)[, lapply(.SD, scale_helper, 100), keyby = Group]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.