R:基于几个条件的总和行

时间:2017-06-11 07:39:14

标签: r conditional aggregate rowsum

我正在研究我的论文,对r知之甚少,所以这个问题的答案可能非常明显。

我的数据集看起来像这样:

county<-c('1001','1001','1001','1202','1202','1303','1303')
naics<-c('423620','423630','423720','423620','423720','423550','423720')
employment<-c(5,6,5,5,5,6,5)
data<-data.frame(county,naics,employment)

对于每个县,我想用naics&#39; 423620&#39;和&#39; 423720&#39;。 (所以两个条件:1。相同的县代码2.这两个naics代码)添加它们的行应该是第一个(&#39; 423620&#39;),第二个(&#39; 423720&应删除#39;)

最终数据集应如下所示:

county2<-c('1001','1001','1202','1303','1303')
naics2<-c('423620','423630','423620','423550','423720')
employment2<-c(10,6,10,6,5)
data2<-data.frame(county2,naics2,employment2)

我尝试用aggregate和rowSum自己做,但由于这两个条件,我到目前为止失败了。非常感谢你。

2 个答案:

答案 0 :(得分:1)

我们可以做到

library(dplyr)
data$naics <- as.character(data$naics)

data %>%
    filter(naics %in% c(423620, 423720)) %>% group_by(county) %>% 
    summarise(naics = "423620", employment = sum(employment)) %>%
    bind_rows(., filter(data, !naics  %in% c(423620, 423720)))
# A tibble: 5 x 3
#   county  naics employment
#  <fctr>  <chr>      <dbl>
#1   1001 423620         10
#2   1202 423620         10
#3   1303 423620          5
#4   1001 423630          6
#5   1303 423550          6

答案 1 :(得分:0)

有了这样的条件,我先写一个小帮手,然后把它传递给dplyr mutate:

# replace 423720 by 423620 only if both exist
onlyThoseNAICS <- function(v){
  if( ("423620" %in% v) & ("423720" %in% v) ) v[v == "423720"] <- "423620"
  v
}

data %>% 
  dplyr::group_by(county) %>% 
  dplyr::mutate(naics = onlyThoseNAICS(naics)) %>% 
  dplyr::group_by(county, naics) %>% 
  dplyr::summarise(employment = sum(employment)) %>% 
  dplyr::ungroup()