簡體   English   中英

在 R 中創建數據透視表

[英]Create pivot table in R

我正在嘗試在 R 中創建一個數據透視表。

我知道類似的問題有很多不同的問題,但我已經嘗試過他們的解決方案,但似乎沒有用。

所以,你能幫我從這個數據框中得到嗎

物種 站 1 站 2 3號站
物種1 5 5 5
物種2 10 52 0
物種4 0 3 8
物種2 20 15 5
物種3 4 5 5
物種2 6 9 2
物種1 5 10 5

到這個數據框

物種 站 1 站 2 3號站
物種1 10 15 10
物種2 36 76 7
物種4 0 3 8
物種3 4 5 5

感謝您的幫助!

看起來我們的 R 基礎用戶正在成為 SO 的垂死者。 這是一個沒有添加任何額外包的單行解決方案。

xy <- read.table(text = "Species    Station1    Station2    Station3
Species1    5   5   5
Species2    10  52  0
Species4    0   3   8
Species2    20  15  5
Species3    4   5   5
Species2    6   9   2
Species1    5   10  5", sep = "\t", header = TRUE)

aggregate(. ~ Species, data = xy, FUN = sum)

    Species Station1 Station2 Station3
1 Species1        10       15       10
2 Species2        36       76        7
3 Species3         4        5        5
4 Species4         0        3        8

您可以使用dplyr

library(dplyr)

df <- tribble(
  ~Species, ~Station1, ~Station2, ~Station3,
  "Species1",   5,  5,  5,
  "Species2",   10, 52, 0,
  "Species4",   0,  3,  8,
  "Species2",   20, 15, 5,
  "Species3",   4,  5,  5,
  "Species2",   6,  9,  2,
  "Species1",   5,  10, 5
)

df %>% 
  group_by(Species) %>% 
  summarise(across(everything(), sum))

結果:

# A tibble: 4 × 4
  Species  Station1 Station2 Station3
  <chr>       <dbl>    <dbl>    <dbl>
1 Species1       10       15       10
2 Species2       36       76        7
3 Species3        4        5        5
4 Species4        0        3        8

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM