r - 如何计算和汇总R中小标题中列的值?
问题描述
例如,我有这个小标题:
nationality Other
[1,] White 1 ------> I want to add
[2,] Mexican 0
[3,] American 0
[4,] Asian 1 -------> I want to add
[5,] af 1 -------> I want to add
[6,] American 0
我想以某种方式总结 Other 中的值并创建它自己的小标题:
Other
[1,] 3
我尝试使用 sum(),但它给了我
Error in FUN(X[[i]], ...) :
only defined on a data frame with all numeric variables
除此之外,tally() 给了我这个,它计算列中的行数:
n
1 88
这是代码:
natgroups3 <- ibtclean %>% select(nationality) %>%mutate(Other = ifelse(str_detect(nationality, "af|White|Asian|white|Middle-Eastern"), yes = 1, no = 0)) %>% drop_na()
解决方案
尝试使用tidyverse库。我准备了一个示例代码,它使用您的结构重新创建一个 tibble d,并计算目标 tibble c,其中列other等于 1 的行数。
library(tidyverse)
d <- tribble(~nationality, ~other, 'White', 0, 'Mexican', 1, 'Amrican', 0, 'Asian', 1, 'af', 1)
d
c <- d %>% count(other) %>% filter(other == 1) %>% select('Other' = n)
c
您也可以选择其他列并使用以下代码计算其总和(根据您的业务需要)
library(tidyverse)
d <- tribble(~nationality, ~other, 'White', 0, 'Mexican', 1, 'Amrican', 0, 'Asian', 1, 'af', 1)
d
c <- d %>% select(other) %>% summarise('Other'=sum(other))
c
两个代码片段都产生以下结果
# A tibble: 5 x 2
nationality other
<chr> <dbl>
1 White 0
2 Mexican 1
3 Amrican 0
4 Asian 1
5 af 1
# A tibble: 1 x 1
Other
<dbl>
1 3
我希望这些片段能解决您的问题
推荐阅读
- python - 如何将 Header 和 Trailer 从文件移动到另一个文件?
- ssrs-2012 - 有没有办法从多个数据集中获取所有列值的列表
- kubernetes - 如何提供 2 个不同的 IP 范围?--pod-network-cidr= 用于多个 IP 范围
- machine-learning - 如何在 Pytorch 中为优化器动态添加新参数?
- java - HandlerInterceptor 不适用于匿名
- sql - 如何使用 where 子句中的子查询修复 Oracle“不是 GROUP BY 表达式”错误
- c# - 异步 / 等待 TCP 侦听器从相机保存图像
- css - 无法水平居中列表
- c++ - 删除最后一个节点,并将尾部更新到最后一个节点
- google-maps - Google Geocoder API 返回的地址不正确