簡體   English   中英

根據行數不同的另一個數據框的值將值分配給一個數據框的列

[英]Assign values to a column of one data frame based on values of another data frame with different number of rows

假設我有兩個數據幀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

非常感謝您如何進行任何幫助。

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

暫無
暫無

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

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