汇总 and/or 将相似的行转置为列
Summarize and/or Transpose similar rows into columns
我有一个很大的 data.frame 这种格式:
Location Crop Acres
Plot 1 Wheat 6
Plot 1 Canola 10
Plot 1 Barley 50
Plot 2 Canola 100
Plot 2 Wheat 25
每个位置可能有很多作物,有些可能只有 1 个。我想以某种方式总结并将作物和英亩转移到一个位置,以便新的 data.frame 看起来像
Location Crop1 Acres1 Crop2 Acres2 Crop3 Acres3
Plot 1 Wheat 6 Canola 10 Barley 50
Plot 2 Canola 100 Wheat 25 NA NA
显然,Crop 和 Acres 列不能相同,所以会有 Crop1、Acres1、Crop2、Acres2 等等。
我试过数据透视表,但没有得到我需要的结果,或者我没有使用正确的代码。
tidyverse
这样的事情怎么样:
library(dplyr)
library(tidyr)
data %>%
# first ensure you do not have some dupes
group_by(Location, Crop) %>%
summarise(Acres = sum(Acres)) %>%
# here you add a column that give the "position" by group
group_by(Location) %>%
mutate(n_ = 1:n()) %>%
# lastly you pivot to have data from long to wide format
pivot_wider( names_from = c(n_),
values_from = c(Crop,Acres))
# A tibble: 2 x 7
# Groups: Location [2]
Location Crop_1 Crop_2 Crop_3 Acres_1 Acres_2 Acres_3
<chr> <chr> <chr> <chr> <dbl> <dbl> <dbl>
1 Plot 1 Barley Canola Wheat 50 10 6
2 Plot 2 Canola Wheat NA 100 25 NA
我有一个很大的 data.frame 这种格式:
Location Crop Acres
Plot 1 Wheat 6
Plot 1 Canola 10
Plot 1 Barley 50
Plot 2 Canola 100
Plot 2 Wheat 25
每个位置可能有很多作物,有些可能只有 1 个。我想以某种方式总结并将作物和英亩转移到一个位置,以便新的 data.frame 看起来像
Location Crop1 Acres1 Crop2 Acres2 Crop3 Acres3
Plot 1 Wheat 6 Canola 10 Barley 50
Plot 2 Canola 100 Wheat 25 NA NA
显然,Crop 和 Acres 列不能相同,所以会有 Crop1、Acres1、Crop2、Acres2 等等。
我试过数据透视表,但没有得到我需要的结果,或者我没有使用正确的代码。
tidyverse
这样的事情怎么样:
library(dplyr)
library(tidyr)
data %>%
# first ensure you do not have some dupes
group_by(Location, Crop) %>%
summarise(Acres = sum(Acres)) %>%
# here you add a column that give the "position" by group
group_by(Location) %>%
mutate(n_ = 1:n()) %>%
# lastly you pivot to have data from long to wide format
pivot_wider( names_from = c(n_),
values_from = c(Crop,Acres))
# A tibble: 2 x 7
# Groups: Location [2]
Location Crop_1 Crop_2 Crop_3 Acres_1 Acres_2 Acres_3
<chr> <chr> <chr> <chr> <dbl> <dbl> <dbl>
1 Plot 1 Barley Canola Wheat 50 10 6
2 Plot 2 Canola Wheat NA 100 25 NA