【问题标题】:Merging Datasets Without Losing Data合并数据集而不丢失数据
【发布时间】:2018-05-17 01:50:14
【问题描述】:

我有几个数据集,在某些点对物种进行了不同的数值观察。但是,如果在某个点上没有观察到某个物种,那么该点在该物种的数据中就不存在。我想合并这些数据集,以便分析每个点的物种组成,但如果在该点没有观察到物种,则希望输入 0 值。

不知道该怎么做。尝试使用合并功能,但如果在其中一个物种数据集中没有观察到该点,则该点丢失。

物种 1:

Point, Species1
1, 19
3, 12
4, 11
6, 23

物种 2:

Point, Species2
2, 10
3, 20
5, 12
6, 25

期望的结果:

Point, Species1, Species2
1, 19, 0
2, 0, 10
3, 12, 20
4, 11, 0
5, 0, 12
6, 23, 25

【问题讨论】:

  • 请包括示例数据,以显示您的数据在您的问题中的外观。
  • 只需merge 并用ifelse(is.na(.),0,.) 修复孔。
  • 使用all=TRUE

标签: r merge


【解决方案1】:

你只需要mergeall=True

s=merge(df1,df2,on='Point',all=T)
s[is.na(s)]=0
s
  Point Species1 Species2
1     1       19        0
2     2        0       10
3     3       12       20
4     4       11        0
5     5        0       12
6     6       23       25

【讨论】:

    【解决方案2】:

    你可以使用dplyr::full_join():

    require(tidyverse)
    
    df1 <- data.frame(Point = c(1,3,4,6), Species1 = c(19,12,11,23))
    df2 <- data.frame(Point = c(2,3,5,6), Species2 = c(10,20,12,25))
    
    df1 %>% 
      full_join(df2) %>% 
      replace_na(list(Species1=0, Species2=0)) %>%
      arrange(Point)
    
      Point Species1 Species2
    1     1       19        0
    2     2        0       10
    3     3       12       20
    4     4       11        0
    5     5        0       12
    6     6       23       25
    

    【讨论】:

    • 我更喜欢 'join_all(list(dfs), type = "full)' 用于以后需要加入更多 data.frames 的情况。
    猜你喜欢
    • 2017-09-08
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 2021-11-28
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多