我试图从行计算中改变一个新变量,rowSums
如下所示
iris %>%
mutate_(sumVar =
iris %>%
select(Sepal.Length:Petal.Width) %>%
rowSums)
Run Code Online (Sandbox Code Playgroud)
结果是"sumVar"被截断为其第一个值(10.2):
Source: local data frame [150 x 6]
Groups: <by row>
Sepal.Length Sepal.Width Petal.Length Petal.Width Species sumVar
1 5.1 3.5 1.4 0.2 setosa 10.2
2 4.9 3.0 1.4 0.2 setosa 10.2
3 4.7 3.2 1.3 0.2 setosa 10.2
4 4.6 3.1 1.5 0.2 setosa 10.2
5 5.0 3.6 1.4 0.2 setosa 10.2
6 5.4 3.9 1.7 0.4 setosa 10.2
..
Warning message:
Truncating vector to length 1
Run Code Online (Sandbox Code Playgroud)
它应该rowwise
适用吗?或者在这些计算中使用什么是正确的动词.
编辑:
更具体地说,是否有任何方法可以实现内联自定义功能dplyr
?
我想知道是否有可能做类似的事情:
iris %>%
mutate(sumVar = colsum_function(Sepal.Length:Petal.Width))
Run Code Online (Sandbox Code Playgroud)
tal*_*lat 103
这是一种解决方法,但可以使用
iris %>% mutate(sumVar = rowSums(.[1:4]))
Run Code Online (Sandbox Code Playgroud)
正如在注释中所写,您也可以使用select
mutate内部来获取您想要总结的列
iris %>%
mutate(sumVar = rowSums(select(., contains("Sepal")))) %>%
head
Run Code Online (Sandbox Code Playgroud)
要么
iris %>%
mutate(sumVar = select(., contains("Sepal")) %>% rowSums()) %>%
head
Run Code Online (Sandbox Code Playgroud)
Dav*_*tti 12
更复杂的方式是:
iris %>% select(Sepal.Length:Petal.Width) %>%
mutate(sumVar = rowSums(.)) %>% left_join(iris)
Run Code Online (Sandbox Code Playgroud)
HBa*_*Bat 11
您可以使用rowwise()
功能:
iris %>%
rowwise() %>%
mutate(sumVar = sum(c_across(Sepal.Length:Petal.Width)))
#> # A tibble: 150 x 6
#> # Rowwise:
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species sumVar
#> <dbl> <dbl> <dbl> <dbl> <fct> <dbl>
#> 1 5.1 3.5 1.4 0.2 setosa 10.2
#> 2 4.9 3 1.4 0.2 setosa 9.5
#> 3 4.7 3.2 1.3 0.2 setosa 9.4
#> 4 4.6 3.1 1.5 0.2 setosa 9.4
#> 5 5 3.6 1.4 0.2 setosa 10.2
#> 6 5.4 3.9 1.7 0.4 setosa 11.4
#> 7 4.6 3.4 1.4 0.3 setosa 9.7
#> 8 5 3.4 1.5 0.2 setosa 10.1
#> 9 4.4 2.9 1.4 0.2 setosa 8.9
#> 10 4.9 3.1 1.5 0.1 setosa 9.6
#> # ... with 140 more rows
Run Code Online (Sandbox Code Playgroud)
"c_across()
使用整洁的选择语法,因此您可以简洁地选择许多变量"'
最后,如果你愿意,你可以%>% ungroup
在最后使用从 rowwise 退出。
添加@ docendodiscimus的评论作为答案.+1给他!
iris %>% mutate(sumVar = rowSums(select(., contains("Sepal"))))
Run Code Online (Sandbox Code Playgroud)