简体   繁体   English

如何使用 purrr 替换 R 中的修改循环?

[英]How to use purrr to replace a modifying for loop in R?

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:我想将每个组缩放到 100 的中位数,并用新值替换Value列,因此数据框如下所示:

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:

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.我可以用for循环来做到这一点,但如果可能的话,我想改用purrr Is there a straightforward way to do it using purrr , or is a for loop the better way to go here?是否有使用purrr的直接方法,或者for循环是更好的方法?

Loop for is not good way, but I don't understand why you want to use purr. Loop for 不是好方法,但我不明白你为什么要使用 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.或者你可以使用data.table。 Something like this:像这样的东西:

as.data.table(df)[, lapply(.SD, scale_helper, 100), keyby = Group]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM