【问题标题】:Assign values to a column of one data frame based on values of another data frame with different number of rows根据具有不同行数的另一个数据框的值将值分配给一个数据框的列
【发布时间】:2018-05-21 10:12:24
【问题描述】:

假设我有两个数据框,df_ydf_x

df_y <- data.frame(int_area = c(0.00503201, 0.66491063, 1.40633472, 2.76595972, 
        3.38315429, 3.38842563, 4.43895167, 6.85371330, 10.17257506, 17.27029774), 
                  count=c(2,3,6,5,6,5,3,5,1,1))

df_x <- data.frame(int_area = c(0.00503201, 0.66491063, 1.40633472, 2.76595972, 
        3.38315429, 3.38842563, 4.43895167, 6.85371330, 10.17257506, 17.27029774)

我想基于df_y$int_areadf_y$count 创建列df_x$count。像

if df_y$int_area = df_x$int_area then df_x$count = df_x$count. 

我尝试使用ifelse

df_x$count = ifelse(df_y$int_area == df_x$int_area, df_y$count, NA)

但我收到以下错误消息:

警告信息: 在 int_area$int_area == y$int_area : 较长的对象长度不是较短对象长度的倍数

然后我尝试使用 %in% 但不是 == 但我得到了这个错误:

$&lt;-.data.frame(*tmp*, count, value = c(2L, NA, 6L, 5L, : 替换有497行,数据有57599

非常感谢任何有关如何进行的帮助。

【问题讨论】:

  • 我认为这是一个合并(或“左连接”) - merge(df_x, df_y, all.x=TRUE) 做你想做的事吗?尽管尝试合并具有多个小数位的数字可能是可疑的。

标签: r dataframe


【解决方案1】:
library(dplyr)
df_x <- df_x %>% left_join(df_y, by = c('int_area' = 'int_area'))

> df_x
      int_area count
1   0.00503201     2
2   0.66491063     3
3   1.40633472     6
4   2.76595972     5
5   3.38315429     6
6   3.38842563     5
7   4.43895167     3
8   6.85371330     5
9  10.17257506     1
10 17.27029774     1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-21
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    相关资源
    最近更新 更多