簡體   English   中英

比較 R 中 2 個不同數據幀中的多列

[英]Compare multiple columns in 2 different dataframes in R

我正在嘗試比較 R 中兩個不同數據幀中的多個列。這在之前的論壇上已經解決( 比較兩列的組並返回索引匹配 R )但這是一個不同的場景:我試圖比較列是否在dataframe 1位於dataframe 2的 2 列范圍之間。 match, merge, join, intersect等功能在這里不起作用。 我一直在嘗試使用purr::pluck但沒有走多遠。 數據幀具有不同的大小。

下面是一個例子:

temp1.df <- mtcars

temp2.df <- data.frame(
  Cyl = sample (4:8, 100, replace = TRUE),
  Start = sample (1:22, 100, replace = TRUE),
  End = sample (1:22, 100, replace = TRUE)
)

temp1.df$cyl <- as.character(temp1.df$cyl)
temp2.df$Cyl <- as.character(temp2.df$Cyl)

我的嘗試:

temp1.df <- temp1.df %>% mutate (new_mpg = case_when (
  temp1.df$cyl %in% temp2.df$Cyl & temp2.df$Start <= temp1.df$mpg & temp2.df$End >= temp1.df$mpg ~ 1
))

錯誤:

Error in mutate_impl(.data, dots) : 
  Column `new_mpg` must be length 32 (the number of rows) or one, not 100

預期結果:

  1. 比較 temp1.df$cyl 和 temp2.​​df$Cyl。 如果它們匹配,則 -->
  2. 檢查 temp1.df$mpg 是否在 temp2.​​df$Start 和 temp2.​​df$End 之間 -->
  3. 如果是,則創建一個值為 1 的新變量 new_mpg。

在這里很難顯示確切的預期輸出。

我意識到我可以為temp1.df每一行循環這個,但原始temp2.df有超過 250,000 行。 一個有效的解決方案將不勝感激。

謝謝

temp1.df$new_mpg<-apply(temp1.df, 1, function(x) {
  temp<-temp2.df[temp2.df$Cyl==x[2],] 
  ifelse(any(apply(temp, 1, function(y) {
    dplyr::between(as.numeric(x[1]),as.numeric(y[2]),as.numeric(y[3]))
  })),1,0)
})

請注意,這對實際數據的組織做出了一些假設(特別是,我無法調用apply的列名,因此我使用了索引 - 這可能會發生很大變化,因此您可能想要重新排列數據在接收它和調用apply ,或者可能在apply改變它的組織,例如,通過apply(temp1.df[,c("mpg","cyl")]...

無論如何,這會將您的數據集分成幾行,並將每一行與具有相同 Cyl 計數的第二個數據集的子集進行比較。 在這個子集,它會檢查是否any的MPG此行的下降between (從dplyrStartEnd ,並返回1,如果是(或者0,如果沒有)。 然后所有這些 1 和 0 作為(命名)向量返回,可以放入temp1.df$new_mpg

我猜有一種方法可以用rowwise做到這rowwise ,但我永遠無法讓它正常工作......

暫無
暫無

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

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