我有以下資料框morphology:
month site depth num.core num.plant num.leaf
<chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 Oct SB 12 1 1 5
2 Oct SB 12 1 2 29
3 Oct SB 12 1 3 7
4 Oct SB 12 2 1 9
5 Oct SB 12 2 2 4
6 Oct SB 12 2 3 13
我的目標是在設定日期 ( ) 和每個核心 ( ) 計算植物 ( ) 的數量。num.plantnum.coremonthdepth
我已經對資料框進行了分組,并根據需要計算了每個核心的植物數量:
morpho.group <- morphology %>%
group_by(month, site, num.core, depth) %>%
count(month,site,num.core,depth, name = "plant.count.Xcore")
month site num.core depth plant.count.Xcore
<chr> <chr> <dbl> <dbl> <int>
1 Dec D 1 3 4
2 Dec D 2 3 2
3 Dec D 3 3 3
4 Dec D 4 3 3
5 Dec N 1 12 1
6 Dec N 2 12 5
我的問題是我需要對資料幀執行更多操作,morphology例如對每個核心的葉子數求和,例如:
count.morpho <- morphology %>%
group_by(month, site, num.core, depth) %>%
summarise_at(vars("num.leaf", "num.roots"), sum)
month site num.core depth num.leaf num.roots
<chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 Dec D 1 3 11 13
2 Dec D 2 3 17 8
3 Dec D 3 3 14 4
4 Dec D 4 3 40 10
5 Dec N 1 12 3 2
6 Dec N 2 12 40 10
我需要執行這些操作,以便它們繼續并添加到單個資料框,而不是將每個計算列拉到新的資料框。
任何幫助深表感謝 :)
uj5u.com熱心網友回復:
count實際上只是查看n()組的便捷功能,您可以更字面地包含它并添加其他指標。
(僅供參考,您的資料不包括num.roots,因此我將其替換為num.plant此處只是為了演示。)
morphology %>%
group_by(month, site, num.core, depth) %>%
summarize(
plant.count.Xcore = n(),
across(c(num.leaf, num.plant), sum)
) %>%
ungroup()
# # A tibble: 2 x 7
# month site num.core depth plant.count.Xcore num.leaf num.plant
# <chr> <chr> <int> <int> <int> <int> <int>
# 1 Oct SB 1 12 3 41 6
# 2 Oct SB 2 12 3 26 6
僅供參考,summarize_at被across. 注意現在發生了變化:summarize像往常一樣使用,使用across但未分配給某物,單獨使用;第一個 arg to cross 是一組可供選擇的變數,使用類似的方法,select包括c(col1, col2)、starts_with("num")和 negation 這些選項;第二個引數是一個或多個不同方式的函式,類似于summarize_at的函式引數。有關更多詳細資訊,請參閱colwise小插圖。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/427582.html
