首页 > 解决方案 > setdiff(x,y) 错误:返回 x 而不是仅在 x 中而不是在 y 中的值

问题描述

我不确定数据转换备忘intersect()单为什么会setdiff()为我返回错误。我看了其他答案,找不到答案。任何帮助将非常感激!


可重现的例子

我正在使用library(tidyverse)and library(plyr)(我相信它包含在其中,tidyverse但在试图找出错误时,我还是加载了包)。我还在lubridate我的代码中使用了另一部分,所以我添加了它。在我的真实数据中,我在每个表的“代码”列中有很多冗余值,所以我添加了重复值并通过管道distinct()复制了下面的结构。

library(tidyverse) 
library(plyr)
library(lubridate)

# x table
x <- tibble(code = c(1,2,2)) %>% 
  distinct(code)

# y table
y <- tibble(code = c(2,3,3)) %>% 
  distinct(code)

intersect():我想用来intersect()在 x 中生成一个值表,这些值也在 y: 中2。我发现这join()行得通,但如果有人可以分享为什么我没有返回2,我将不胜感激。

# this produces error message "Length of logical index must be 1 or 2, not 0"
intersect(x, y) 

# but this seems to work and returns a table with `2` which is what I want
intersect_solution <- join(x, y, type = "inner")

setdiff():我想用来setdiff()在 x 中生成不在 y: 中的值的表1。我被困在这里,完全不知道为什么这不起作用。

# this produces all of x: `1` and `2`
setdiff(x, y) 

问题编辑:我的代码中有错字并修复了它。以下进一步补充:

标签: r

解决方案


当你附上lubridate

library(lubridate)

表明

Attache Paket:'lubridate'</p>

以下对象被“package:dplyr”屏蔽:

intersect, setdiff, union

以下对象被“package:base”屏蔽:

date, intersect, setdiff, union

仍然从dplyr使用中访问它们dplyr::intersectdplyr::setdiff并且dplyr::union


推荐阅读