r

时间:2015-12-13 04:39:08

标签: r dataframe rowsum

我有一个复杂的数据框,最小的例子如下:

df <- structure(list(District = c("Adilabad", "Adilabad", "Adilabad", 
                        "Adilabad", "Adilabad", "Adilabad", "Adilabad", "Adilabad", "Adilabad", 
                        "Adilabad"), Subdistt = c("Adilabad", "Adilabad", "Adilabad", 
                        "Tamsi", "Tamsi", "Tamsi", "Tamsi", "Tamsi", "Tamsi", "Tamsi"
                        ), TRU = c("Total", "Rural", "Urban", "Total", "Rural", "Urban", 
                        "Rural", "Rural", "Urban", "Urban"), Level = c("District", "District", 
                        "District", "Sub-District", "Sub-District", "Sub-District", "Village", 
                        "Village", "Town", "Town"), No_HH = c(1277, 364, 913, 
                        1277, 364, 913, 117, 247, 614, 299)), .Names = c("District", 
                        "Subdistt", "TRU", "Level", "No_HH"), row.names = c(NA, 10L), class = "data.frame")

看起来像这样:

   District Subdistt   TRU        Level No_HH
1  Adilabad Adilabad Total     District  1277
2  Adilabad Adilabad Rural     District   364
3  Adilabad Adilabad Urban     District   913
4  Adilabad    Tamsi Total Sub-District  1277
5  Adilabad    Tamsi Rural Sub-District   364
6  Adilabad    Tamsi Urban Sub-District   913
7  Adilabad    Tamsi Rural      Village   117
8  Adilabad    Tamsi Rural      Village   247
9  Adilabad    Tamsi Urban         Town   614
10 Adilabad    Tamsi Urban         Town   299

某种方式中的每个后续列都是前一列的一种子集。我必须验证农村,城市和总体水平的分区和区的总和。

例如:第7行和第8行的总和等于第5行中的值。第5行是Rural Sub-Distrit。随着我们扩展df,我有许多农村分区。所有农村分区的总和在农村区,即第2排。

最小预期输出如下:

  District Subdistt   TRU        Level No_HH
1 Adilabad    Tamsi Rural Sub-District   364
2 Adilabad    Tamsi Urban Sub-District   913

364是上述最小示例中给出的117 + 247的和,913是最小示例中给出的行614 + 299的总和。

目前,我能够将特定值子集化,但不知道如何根据这些复杂的选择求和。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

我们可以尝试

library(dplyr)
df %>%
    filter(Level=='Sub-District' & TRU != 'Total')
#  District Subdistt   TRU        Level No_HH
#1 Adilabad    Tamsi Rural Sub-District   364
#2 Adilabad    Tamsi Urban Sub-District   913

如果我们需要通过sum ming获得相同的输出,

df %>%
    filter(!grepl('District', Level)) %>% 
    group_by(District, Subdistt,TRU) %>%
    summarise(No_HH= sum(No_HH)) %>%
    mutate(Level= 'Sub_District')
#  District Subdistt   TRU No_HH        Level
#     (chr)    (chr) (chr) (dbl)        (chr)
# 1 Adilabad    Tamsi Rural   364 Sub_District
# 2 Adilabad    Tamsi Urban   913 Sub_District