如何标记 R 中第一次出现的值 [英] How to label the first occurrence of a value in R

查看:45
本文介绍了如何标记 R 中第一次出现的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道使用 match() 会提取变量的第一次出现,但是如何创建一个新列来标记第一次出现?

I know using match() will extract the first occurrence of a variable, but how can I create a new column labeling the first occurrence?

例如我怎么能得到:

example <- data.frame(id = c(1,1,1,2,3,4), label = c(1,0,0,1,1,1))

提前致谢!

推荐答案

An option with duplicated in base R

An option with duplicated in base R

example$label <- +(!duplicated(example$id))

-输出

example
#  id label
#1  1     1
#2  1     0
#3  1     0
#4  2     1
#5  3     1
#6  4     1

duplicated 返回一个逻辑列,其中id"的重复元素为 TRUE,非重复元素为 FALSE,即第一次出现.否定 (!) 反转 TRUE ->FALSE,反之亦然,然后使用 +as.integer

duplicated returns a logical column with TRUE for duplicate elements of 'id' and FALSE for non-duplicates i.e. the first occurrence. Negating (!) reverses the TRUE -> FALSE and viceversa, then coerce it to binary with + or as.integer

这篇关于如何标记 R 中第一次出现的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆