[英]dplyr use both rowwise and df-wise values in a mutate
你如何执行rowwise
它使用值从其他行(在dplyr /整齐的风格)操作? 假设我有这个df:
df <- data_frame(value = c(5,6,7,3,4),
group = c(1,2,2,3,3),
group.to.use = c(2,3,3,1,1))
我想创建一个新变量new.value,它等于每行的当前值加上“group”等于该行的“group.to.use”的行的最大值。 所以对于第一行
new.value = 5 + (max(value[group === 2])) = 5 + 7 = 12
期望的输出:
# A tibble: 5 x 4
value group group.to.use new.value
<dbl> <dbl> <dbl> <dbl>
1 5. 1. 2. 12.
2 6. 2. 3. 10.
3 7. 2. 3. 11.
4 3. 3. 1. 8.
5 4. 3. 1. 9.
伪代码:
df %<>%
mutate(new.value = value + max(value[group.to.use == <group.for.this.row>]))
在行方式操作中,您可以引用整个data.frame .
使用正常语法的data.frame中的整列.$colname
或.[['col.name']]
:
df %>%
rowwise() %>%
mutate(new.value = value + max(.$value[.$group == group.to.use])) %>%
ungroup()
# # A tibble: 5 x 4
# value group group.to.use new.value
# <dbl> <dbl> <dbl> <dbl>
# 1 5 1 2 12
# 2 6 2 3 10
# 3 7 2 3 11
# 4 3 3 1 8
# 5 4 3 1 9
或者,您可以预先计算每个组的最大值,然后执行左连接:
df.max <- df %>% group_by(group) %>% summarise(max.value = max(value))
df %>%
left_join(df.max, by = c('group.to.use' = 'group')) %>%
mutate(new.value = value + max.value) %>%
select(-max.value)
# # A tibble: 5 x 4
# value group group.to.use new.value
# <dbl> <dbl> <dbl> <dbl>
# 1 5 1 2 12
# 2 6 2 3 10
# 3 7 2 3 11
# 4 3 3 1 8
# 5 4 3 1 9
使用基数R,我们可以使用ave
,我们计算每个group
max
,并添加与组match
的相应value
。
df$new.value <- with(df, value +
ave(value, group, FUN = max)[match(group.to.use, group)])
df
# A tibble: 5 x 4
# value group group.to.use new.value
# <dbl> <dbl> <dbl> <dbl>
#1 5.00 1.00 2.00 12.0
#2 6.00 2.00 3.00 10.0
#3 7.00 2.00 3.00 11.0
#4 3.00 3.00 1.00 8.00
#5 4.00 3.00 1.00 9.00
这是一个base R
的选项
df$new.value <- with(df, value + vapply(group.to.use, function(x)
max(value[group == x]), numeric(1)))
df$new.value
#[1] 12 10 11 8 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.