简体   繁体   English

在 R 中制作具有多列的数据透视表

[英]Making a pivot table with multiple columns in R

I have a table called "Trends" that looks something like this我有一个名为“趋势”的表,看起来像这样

Project   Area      Animal     Trend
A        Canada     Bird       1.5
A        USA        Mammal     -0.6
A        Mexico     Bird       -2.5
B        Mexico     Bird       0.7
B        Canada     Reptile    2.5
B        Canada     Bird       -0.3

What I want is to make a summary table that will look something like this:我想要的是制作一个看起来像这样的汇总表:

Animal     Area       ATrend      BTrend
  Bird     Canada      1.5          -0.3
  Bird     Mexico      -2.5         0.7
  Mammal    USA        -0.6
  Reptile   Canada                  2.5

I have 4 different projects, over 20 different areas and over 200 different animals, so need to find code that can adapt to all of it without specifying each grouping.我有 4 个不同的项目,20 多个不同的区域和 200 多种不同的动物,因此需要找到可以适应所有项目的代码,而无需指定每个分组。

I was trying to use cast function to make a pivot table but I'm struggling to add more than one column (ie Animal and Area).我试图使用强制转换函数来制作数据透视表,但我正在努力添加多于一列(即动物和区域)。 What I tried was:我尝试的是:

cast(Trends, Animal~Project)

But this only gave me the count of how many animals were recorded in each project, and obviously did not take into account the different areas.但这只是给我统计了每个项目记录了多少动物,显然没有考虑到不同的区域。 I am very new to R and don't know much, so I would greatly appreciate a detailed answer for a newbie :)我对 R 很陌生,知道的不多,所以我非常感谢新手的详细回答:)

An option would be pivot_wider一个选项是pivot_wider

library(tidyr)
library(dplyr)
library(stringr)
Trends %>% 
    mutate(Project = str_c("Trend", Project)) %>%
    pivot_wider(names_from = Project, values_from = Trend)
# A tibble: 4 x 4
#  Area   Animal  TrendA TrendB
#  <chr>  <chr>    <dbl>  <dbl>
#1 Canada Bird       1.5   -0.3
#2 USA    Mammal    -0.6   NA  
#3 Mexico Bird      -2.5    0.7
#4 Canada Reptile   NA      2.5

data数据

Trends <- structure(list(Project = c("A", "A", "A", "B", "B", "B"), Area = c("Canada", 
"USA", "Mexico", "Mexico", "Canada", "Canada"), Animal = c("Bird", 
"Mammal", "Bird", "Bird", "Reptile", "Bird"), Trend = c(1.5, 
-0.6, -2.5, 0.7, 2.5, -0.3)), class = "data.frame", row.names = c(NA, 
-6L))

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

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