dplyr - 使用mutate()像rowmeans() [英] dplyr - using mutate() like rowmeans()
本文介绍了dplyr - 使用mutate()像rowmeans()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据行的平均值计算数据框的新变量。
例如:
data < - data.frame(id = c(101,102,103),a = c(1,2,3) ,b = c(2,2,2),c = c(3,3,3))
我想使用mutate来创建变量d,它是a,b和c的意思。我想通过以d = mean(a,b,c)的方式选择列,我也需要使用变量范围(如dplyr中的)d = mean(a:c)。 / p>
当然
mutate(data,c = mean ,b))
或
mutate(data,c = rowMeans(a,b))
你能给我一些提示吗?
关心
解决方案
您正在寻找
data%> ;%
rowwise()%>%
mutate(c = mean(c(a,b)))
#id abc
#(dbl) (dbl)(dbl)(dbl)
#1 101 1 2 1.5
#2 102 2 2 2.0
#3 103 3 2 2.5
或
库(purrr)
data%>%
rowwise()%>%
mutate(c = lift_vd(mean)(a,b))
I can't find the answer anywhere.
I would like to calculate new variable of data frame which is based on mean of rows.
For example:
data <- data.frame(id=c(101,102,103), a=c(1,2,3), b=c(2,2,2), c=c(3,3,3))
I want to use mutate to make variable d which is mean of a,b and c. And I would like to be able to make that by selecting columns in way d=mean(a,b,c), and also I need to use range of variables (like in dplyr) d=mean(a:c).
And of course
mutate(data, c=mean(a,b))
or
mutate(data, c=rowMeans(a,b))
doesn't work.
Can you give me some tip?
Regards
解决方案You're looking for
data %>% rowwise() %>% mutate(c=mean(c(a,b))) # id a b c # (dbl) (dbl) (dbl) (dbl) # 1 101 1 2 1.5 # 2 102 2 2 2.0 # 3 103 3 2 2.5
or
library(purrr) data %>% rowwise() %>% mutate(c=lift_vd(mean)(a,b))
这篇关于dplyr - 使用mutate()像rowmeans()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!