首页 文章

基于具有不同行数的另一数据帧的值将值分配给一个数据帧的列

提问于
浏览
1

假设我有两个数据帧, 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% 而不是==但我得到了这个错误:

$ < - . data.frame中的错误(* tmp *,count,value = c(2L,NA,6L,5L,:替换有497行,数据有57599)

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

1 回答

  • 0
    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
    

相关问题