簡體   English   中英

在 R 中創建一個新的 dataframe,這是通過比較來自其他兩個不同長度的數據庫的不同排序列而產生的

[英]Create a new dataframe in R resulting from comparison of differently ordered columns from two other databases with different lengths

我有這兩個 dataframe CDD26_FF (5593 行)和 CDD_HI (5508 行)具有如下結構(列)。 CDD 是“連續干旱日”,兩張表顯示了遠期 (FF) 和歷史時期 (HI) 的物種暴露於 CDD。

我只想關注“Biom”和“Species_name”列。

如您所見,這兩個表具有相同的“Species_names”和相同的“Biom”(世界上具有相同氣候條件的地區)。 “Biom”值從 0 到 15。順便說一下,“Species_name”並不總是出現在兩個表中(例如 Abromoco_ben); 此外,這兩個表並不總是具有“Species_name”和“Biom”的組合(組合只是屬於該 Biom 的同一物種的種群)

CDD26_FF:

CDD26_FF 面積單元 Area_total 生物 物種名稱 AreaCellSuAreaTotal
1 1 13 10 Abrocomo_ben 0.076923
1 1 8 1 阿布羅莫星 0.125000
1 1 30 10 阿布羅莫星 0.033333
1 2 10 1 Abrothrix_an 0.200000
1 1 44 10 Abrothrix_an 0.022727
1 3 6 2 Abrothrix_je 0.500000
1 1 7 12 Abrothrix_lo 0.142857

CDD_HI

CDD_HI 面積單元 Area_total 生物 物種名稱 AreaCellSuAreaTot_HI
1 1 8 1 阿布羅莫星 0.125000
1 5 30 10 阿布羅莫星 0.166666
1 1 5 2 阿布羅莫星 0.200000
1 1 10 1 Abrothrix_an 0.100000
1 1 44 10 Abrothrix_an 0.022727
1 6 18 1 Abrothrix_je 0.333333
1 1 23 4 Abrothrix_lo 0.130434

我想突出顯示與“Species_name”和“Biom”具有相同匹配的行:在示例中,它們是 CDD26_FF 中的第 3、4、5 行,分別與 CDD_HI 中的第 2、4、5 行匹配。 我想將這些行存儲在一個新表中,但我不僅想存儲“Species_name”和“Biom”列(就像“compare()”function 似乎一樣),還想存儲所有其他列。

更准確地說,我想從突出顯示的行中計算“AreaCellSuAreaTot”/“AreaCellSuAreaTot_HI”的比率。

我怎樣才能做到這一點? 除了“compare()”之外,我嘗試了一個“for”循環,但是表格的長度不同,所以我嘗試了一個 3 嵌套的 for 循環,仍然沒有結果。 我還嘗試了“compareDF()”和“semi_join()”。 到現在還沒有結果。 謝謝您的幫助。

您可以使用內部連接(由dplyr提供)。 內連接返回存在於表/data.frames 和匹配條件的所有數據集(在這種情況下:匹配“Biom”和“Species_name”)。

隨后很容易使用mutate計算一些比率:

library(dplyr)

cdd26_f %>%
  inner_join(cdd_hi, by=c("Biom", "Species_name")) %>%
  mutate(ratio = AreaCellSuAreaTotal/AreaCellSuAreaTot_HI) %>%
  select(Biom, Species_name, ratio)

返回

# A tibble: 4 x 3
   Biom Species_name ratio
  <dbl> <chr>        <dbl>
1     1 Abrocomo_cin 1    
2    10 Abrocomo_cin 0.200
3     1 Abrothrix_an 2    
4    10 Abrothrix_an 1  

注意:如果您需要所有列或為其他列操作它,請刪除select部分。

數據

cdd26_f <- readr::read_table2("CDD26_FF     AreaCell    Area_total  Biom    Species_name    AreaCellSuAreaTotal
1   1   13  10  Abrocomo_ben    0.076923
1   1   8   1   Abrocomo_cin    0.125000
1   1   30  10  Abrocomo_cin    0.033333
1   2   10  1   Abrothrix_an    0.200000
1   1   44  10  Abrothrix_an    0.022727
1   3   6   2   Abrothrix_je    0.500000
1   1   7   12  Abrothrix_lo    0.142857")

cdd_hi <- readr::read_table2("CDD_HI    AreaCell    Area_total  Biom    Species_name    AreaCellSuAreaTot_HI
1   1   8   1   Abrocomo_cin    0.125000
1   5   30  10  Abrocomo_cin    0.166666
1   1   5   2   Abrocomo_cin    0.200000
1   1   10  1   Abrothrix_an    0.100000
1   1   44  10  Abrothrix_an    0.022727
1   6   18  1   Abrothrix_je    0.333333
1   1   23  4   Abrothrix_lo    0.130434")

暫無
暫無

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

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