比较R中2个不同数据框中的多列

时间:2018-11-14 19:44:47

标签: r dataframe dplyr compare

我正在尝试比较R中两个不同数据框中的多个列。前面已经在论坛(Compare group of two columns and return index matches R)上解决了此问题,但这是另一种情况:我正在尝试比较{{ 1}}在dataframe 1中2列的范围之间。诸如dataframe 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
))
  

预期结果:

     
      
  1. 比较temp1.df $ cyl和temp2.​​df $ Cyl。如果它们匹配,则->
  2.   
  3. 检查temp1.df $ mpg是否在temp2.​​df $ Start和temp2.​​df $ End之间->
  4.   
  5. 如果是,则创建一个值为1的新变量new_mpg。
  6.   

很难在此处显示确切的预期输出。

我意识到我可以循环执行此操作,因此对于Error in mutate_impl(.data, dots) : Column `new_mpg` must be length 32 (the number of rows) or one, not 100 的每一行,但是原始temp1.df的行数超过250,000。一个有效的解决方案将不胜感激。

谢谢

1 个答案:

答案 0 :(得分:1)

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计数的第二个数据集的子集进行比较。在此子集内,它检查此行的mpg的any是否落在between(来自dplyrStartEnd上,如果是,则返回1(或0(如果没有)。然后将所有这些一和零作为(命名的)向量返回,可以将其放入temp1.df$new_mpg中。

我猜测rowwise可以做到这一点,但我永远无法使其正常工作...

相关问题