简体   繁体   English

如何基于唯一条件语句在 R 中创建新列?

[英]How to create a new column in R based on a unique conditional statement?

I am trying to create a new column in a large dataset based on a conditional statement where if a unique value appears in one column, that new column will have a 1 and if it is no longer unique it will have a 0. The data I have appears as such:我正在尝试根据条件语句在大型数据集中创建一个新列,如果一个唯一值出现在一个列中,则该新列将具有 1,如果它不再唯一,它将具有 0。我的数据出现如下:

ex <- data.frame(id = rep(1234, 6), claim = c(14553929, 14553929, 14553929, 2416871, 2416871, 14553947), value = c(27626, 245439, 123435, 764532, 1232467, 3235533))

but I would like it to look like this after the conditional statement:但我希望它在条件语句之后看起来像这样:

ex1 <- data.frame(id = rep(1234, 6), claim = c(14553929, 14553929, 14553929, 2416871, 2416871, 14553947),
                 value = c(27626, 245439, 123435, 764532, 1232467, 3235533), flag = c(1,0,0,1,0,1))

so far I've tried doing: ex$flag <- ifelse(unique(ex$claim), 1, 0) but I keep getting an error.到目前为止,我已经尝试过: ex$flag <- ifelse(unique(ex$claim), 1, 0)但我不断收到错误消息。 I'm not sure if there is an easier way to do this or if I'm missing a basic step, but any help would be greatly appreciated!我不确定是否有更简单的方法可以做到这一点,或者我是否缺少基本步骤,但任何帮助将不胜感激!

We can use duplicated to create the binary column我们可以使用duplicated创建二进制列

ex$flag <-  +(!duplicated(ex$claim))
ex$flag
#[1] 1 0 0 1 0 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM