标识列中重复项的第一个实例 [英] Identify the first instance of a duplicate in a column
本文介绍了标识列中重复项的第一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一列名为"A"
A |
---|
狗 |
猫 |
狗 |
绵羊 |
我想创建一个名为"Keep"的新列,该列的第一个重复项的实例值为1以及所有唯一值
I want to create a new column, called 'Keep' that has a 1 for the first instance of a duplicate as well as all unique values
A | 保持 |
---|---|
狗 | 1 |
猫 | 1 |
狗 | 0 |
绵羊 | 1 |
推荐答案
我们可以使用 duplicated
:
df$Keep <- as.integer(!duplicated(df$A))
如果要使用 data.table
进行此操作:
If you want to do this using data.table
:
library(data.table)
setDT(df)[, Keep := as.integer(!duplicated(A))]
df
# A Keep
#1: Dog 1
#2: Cat 1
#3: Dog 0
#4: Sheep 1
数据
df <- structure(list(A = c("Dog", "Cat", "Dog", "Sheep")),
class = "data.frame", row.names = c(NA, -4L))
这篇关于标识列中重复项的第一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文