在R中使用枢轴函数

balp4ylt  于 2023-03-20  发布在  其他
关注(0)|答案(2)|浏览(131)

我想透视数据集ticky::who中从new_sp_m014到newrel_f65的所有列,并为它们指定通用名称:“name”。另外,单元格表示计数案例,因此我使用了变量案例。我下面的代码没有提供我所需的输出。

Code:
#loading tidyverse package
library(tidyverse)
tb_data <- tidyr::who
tb_data

#Part a

#Pivoting all the columns from new_sp_ms014 to newrel_f65
library(magrittr)
library(dplyr)

tb_datap <- tb_data %>% pivot_longer(cols = new_sp_m014:newrel_f65,
               names_to = "name",
               values_to = "cases")

Appropriate output:
#> # A tibble: 76,046 x 6
#> country iso2 iso3 year name cases
#> <chr> <chr> <chr> <int> <chr> <int>
#> 1 Afghanistan AF AFG 1997 new_sp_m014 0
#> 2 Afghanistan AF AFG 1997 new_sp_m1524 10
#> 3 Afghanistan AF AFG 1997 new_sp_m2534 6
#> 4 Afghanistan AF AFG 1997 new_sp_m3544 3
#> 5 Afghanistan AF AFG 1997 new_sp_m4554 5
#> 6 Afghanistan AF AFG 1997 new_sp_m5564 2
#> # ... with 76,040 more row
m1m5dgzv

m1m5dgzv1#

存在NA值,可以使用values_drop_na = TRUE删除(默认为FALSE)

library(tidyr)
pivot_longer(tb_data, cols = new_sp_m014:newrel_f65,
               names_to = "name",
               values_to = "cases", values_drop_na = TRUE)
  • 输出
# A tibble: 76,046 × 6
   country     iso2  iso3   year name         cases
   <chr>       <chr> <chr> <dbl> <chr>        <dbl>
 1 Afghanistan AF    AFG    1997 new_sp_m014      0
 2 Afghanistan AF    AFG    1997 new_sp_m1524    10
 3 Afghanistan AF    AFG    1997 new_sp_m2534     6
 4 Afghanistan AF    AFG    1997 new_sp_m3544     3
 5 Afghanistan AF    AFG    1997 new_sp_m4554     5
 6 Afghanistan AF    AFG    1997 new_sp_m5564     2
 7 Afghanistan AF    AFG    1997 new_sp_m65       0
 8 Afghanistan AF    AFG    1997 new_sp_f014      5
 9 Afghanistan AF    AFG    1997 new_sp_f1524    38
10 Afghanistan AF    AFG    1997 new_sp_f2534    36
# … with 76,036 more rows
gcuhipw9

gcuhipw92#

只需添加na.omit()

tb_datap <- tb_data %>% pivot_longer(cols = new_sp_m014:newrel_f65,
                                     names_to = "name",
                                     values_to = "cases") %>% 
  na.omit()

相关问题