在(col_1 [i],col_2 [i])=(col_1 [j],-col_2 [j])

时间:2020-01-22 08:45:08

标签: r dataframe duplicates

也许我可能错过了一个明显的解决方案,但是这里有:

请考虑以下数据框。我希望创建一个具有TRUE / FALSE值的列,只要满足条件(col_1 [i],col_2 [i])=(col_1 [j],-col_2 [j]),该值就为TRUE。请注意,sum()在这里不起作用,因为可能存在第三个值。 详细说明;我所拥有的是:

col_1 <- c("x", "x", "y", "y", "y", "z", "z")
col_2 <- c(-1, 1, 3, -3, 4, 7, 3)
df <- data.frame(col_1, col_2)

enter image description here

我想要的是:

enter image description here

我认为答案一定是df%>%group_by(x),但我想不出完整的解决方案。

2 个答案:

答案 0 :(得分:1)

这是我的尝试。如您所说,对数据进行分组是必要的。我用col_1和foo定义了组。 foo包含col_2的绝对值。如果观察数大于1并且col_2中的唯一观察数等于2,则您具有正在搜索的对。

group_by(df, col_1, foo = abs(col_2)) %>% 
mutate(check = n() > 1 & n_distinct(col_2) == 2) %>% 
ungroup %>% 
select(-foo)

  col_1 col_2 check
  <fct> <dbl> <lgl>
1 x        -1 TRUE 
2 x         1 TRUE 
3 y         3 TRUE 
4 y        -3 TRUE 
5 y         4 FALSE
6 z         7 FALSE
7 z         3 FALSE

如罗纳克(Ronak)先前所述,可能存在类似情况。

col_1 <- c("x", "x", "y", "y", "y", "z", "z")
col_2 <- c(1, 1, 3, -3, 4, 7, 3) 
df2 <- data.frame(col_1, col_2)

  col_1 col_2
1     x     1
2     x     1
3     y     3
4     y    -3
5     y     4
6     z     7
7     z     3

group_by(df2, col_1, foo = abs(col_2)) %>% 
mutate(check = n() > 1 & n_distinct(col_2) == 2) %>% 
ungroup %>% 
select(-foo)

  col_1 col_2 check
  <fct> <dbl> <lgl>
1 x         1 FALSE
2 x         1 FALSE
3 y         3 TRUE 
4 y        -3 TRUE 
5 y         4 FALSE
6 z         7 FALSE
7 z         3 FALSE

答案 1 :(得分:0)

您可以尝试以下基本R代码,其中定义了自定义函数f以检查总和:

f <- function(v) {
  unique(c(combn(seq(v),2)[,combn(v,2,sum)==0]))
}

dfout <- Reduce(rbind,
                lapply(split(df,df$col_1), 
                       function(v) {
                         v$col_3 <- F
                         v$col_3[f(v$col_2)] <- T
                         v
                       })
)

dfout <- dfout[order(as.numeric(rownames(dfout))),]

这样

> dfout
  col_1 col_2 col_3
1     x    -1  TRUE
2     x     1  TRUE
3     y     3  TRUE
4     y    -3  TRUE
5     y     4 FALSE
6     z     7 FALSE
7     z     3 FALSE
相关问题