R语言 pivot

    技术2022-07-10  154

    relig_income #> # A tibble: 18 x 11 #> religion `<$10k` `$10-20k` `$20-30k` `$30-40k` `$40-50k` `$50-75k` `$75-100k` #> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> #> 1 Agnostic 27 34 60 81 76 137 122 #> 2 Atheist 12 27 37 52 35 70 73 #> 3 Buddhist 27 21 30 34 33 58 62 #> 4 Catholic 418 617 732 670 638 1116 949 #> 5 Don’t k… 15 14 15 11 10 35 21 #> 6 Evangel… 575 869 1064 982 881 1486 949 #> 7 Hindu 1 9 7 9 11 34 47 #> 8 Histori… 228 244 236 238 197 223 131 #> 9 Jehovah… 20 27 24 24 21 30 15 #> 10 Jewish 19 19 25 25 30 95 69

    把除了religion以外的列变量拉长,变成新的income列,其值变成count列

    relig_income %>% pivot_longer(-religion, names_to = "income", values_to = "count")

    结果如下

    #> # A tibble: 180 x 3 #> religion income count #> <chr> <chr> <dbl> #> 1 Agnostic <$10k 27 #> 2 Agnostic $10-20k 34 #> 3 Agnostic $20-30k 60 #> 4 Agnostic $30-40k 81 #> 5 Agnostic $40-50k 76 #> 6 Agnostic $50-75k 137 #> 7 Agnostic $75-100k 122 #> 8 Agnostic $100-150k 109 #> 9 Agnostic >150k 84 #> 10 Agnostic Don't know/refused 96
    Processed: 0.012, SQL: 9