【问题标题】:Add the frequencies based on match between two existing columns from two dataframes根据两个数据帧中两个现有列之间的匹配添加频率
【发布时间】:2016-10-15 06:26:43
【问题描述】:

我有两个数据框 df1df2

df1=data.frame(species=c("Natica", "Turritela", "Anadara", "Arca", "Murex", "Tellina"),
freq=c(20,2,5,40,12,3))

df2=data.frame(species=c("Natica","Tellina"),freq=c(12,2))

只有当df1的第一列与df2匹配时,我想将df2的freq值添加到df1

所以我期待这样的输出:

我的 df1 应该给出以下输出:

        species     freq
   1    Natica        32
   2    Tureitella     2
   3    Anadara        5
   4    Arca          40
   5    Murex         12
   6    Tellina        5 

【问题讨论】:

  • library(dplyr); full_join(df1,df2) %>% group_by(species) %>% summarize(sum(freq))
  • 显示:错误:找不到函数“%>%”
  • 试试install.packages("dplyr"); library(dplyr)
  • 安装包时遇到问题,我使用的是 R 3.2.5

标签: r


【解决方案1】:

您可以执行以下操作: 只要df2 的所有值都包含在df1 中并且不需要包,这种方法就可以工作。

df1[!is.na(match(df1$species,df2$species)),]$freq <- df1[!is.na(match(df1$species,df2$species)),]$freq + df2$freq
> df1
    species freq
1    Natica   32
2 Turritela    2
3   Anadara    5
4      Arca   40
5     Murex   12
6   Tellina    5

【讨论】:

    猜你喜欢
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2020-01-21
    相关资源
    最近更新 更多