简体   繁体   English

R 在 dataframe 中组合行和列

[英]R combine rows and columns within a dataframe

I've looked around for a while trying to figure this out, but I just can't seem to describe my problem concisely enough to google my way out of it.我环顾四周想弄清楚这个问题,但我似乎无法足够简洁地描述我的问题,无法用谷歌搜索解决问题。 I am trying to work with Michigan COVID stats where the data has Detroit listed separately from Wayne County.我正在尝试使用密歇根 COVID 统计数据,其中的数据将底特律与韦恩县分开列出。 I need to add Detroit's numbers to Wayne County's numbers, then remove the Detroit rows from the data frame.我需要将底特律的数字添加到韦恩县的数字,然后从数据框中删除底特律的行。

I have included a screen grab too.我也包括了一个屏幕抓取。 For the purposes of this problem, can someone explain how I can get Detroit City added to Dickinson, and then make the Detroit City rows disappear?出于这个问题的目的,有人可以解释我如何将底特律市添加到狄金森,然后让底特律市行消失吗? Thanks.谢谢。

library(tidyverse)
library(openxlsx)
cases_deaths <- read.xlsx("https://www.michigan.gov/coronavirus/-/media/Project/Websites/coronavirus/Cases-and-Deaths/4-20-2022/Cases-and-Deaths-by-County-2022-04-20.xlsx?rev=f9f34cd7a4614efea0b7c9c00a00edfd&hash=AA277EC28A17C654C0EE768CAB41F6B5.xlsx")[,-5]
# Remove rows that don't describe counties
cases_deaths <- cases_deaths[-c(51,52,101,102,147,148,167,168),]

Code chunk output picture代码块output 图片

You could do:你可以这样做:

cases_deaths %>%
  filter(COUNTY %in% c("Wayne", "Detroit City")) %>%
  mutate(COUNTY = "Wayne") %>%
  group_by(COUNTY, CASE_STATUS) %>%
  summarize_all(sum) %>%
  bind_rows(cases_deaths %>%
            filter(!COUNTY %in% c("Wayne", "Detroit City")))
#> # A tibble: 166 x 4
#> # Groups:   COUNTY [83]
#>    COUNTY  CASE_STATUS  Cases Deaths
#>    <chr>   <chr>        <dbl>  <dbl>
#>  1 Wayne   Confirmed   377396   7346
#>  2 Wayne   Probable     25970    576
#>  3 Alcona  Confirmed     1336     64
#>  4 Alcona  Probable       395      7
#>  5 Alger   Confirmed     1058      8
#>  6 Alger   Probable       658      5
#>  7 Allegan Confirmed    24109    294
#>  8 Allegan Probable      3024     52
#>  9 Alpena  Confirmed     4427    126
#> 10 Alpena  Probable      1272     12
#> # ... with 156 more rows

Created on 2022-04-23 by the reprex package (v2.0.1)reprex package (v2.0.1) 创建于 2022-04-23

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM