如何在 R 的数据框中将第一个唯一记录标记(标记)为 1,其余类似的记录标记为 0 [英] How can I mark (flag) first unique record as 1 and the rest similar records as 0 in data frame in R

查看:29
本文介绍了如何在 R 的数据框中将第一个唯一记录标记(标记)为 1,其余类似的记录标记为 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有关 R 中数据的帮助.如果我至少有一条记录,我将创建新列.我的数据 (df) 如下所示:

I need help with my data in R. I will create new column if I have at least one record. My data (df) look like this:

date adress
28.03 bla
28.03 xyz
17.03 abc
30.03 yxz
24.03 bla 
17.03 abc
23.03 abc
28.03 bla
24.03 bla
24.03 bla

我想创建一个带驾驶的新列,如果日期和地址相同,那么设置 1(在第一个发现的记录中).如果有人去同一个地方的另一个时间(日期),设置1,但如果有人去同一个地方和日期将再次相同的设置0.
像这样:

And I want to create new column with driving, where if date is the same and adress too then set 1 (in first spotted record). If someone goes another time (date) in the same place, set 1, but if someone go to the same place and date will be again the same set 0.
Sth like this:

date adress drive
28.03 bla 1
28.03 xyz 1
17.03 abc 1
30.03 yxz 1
24.03 bla 1 
17.03 abc 0
23.03 abc 1
28.03 bla 0
24.03 bla 0
24.03 bla 0

我使用 dplyr:

df2 <- df %>%
       group_by(date, adress) %>%
       mutate(drive = ifelse(n()>1, 0, 1))

我得到的数据如下,我的第一个发现记录也是 0.

I get data as below and my first spotted record has also 0.

date adress drive
28.03 bla 0
28.03 xyz 1
17.03 abc 0
30.03 yxz 1
24.03 bla 0 
17.03 abc 0
23.03 abc 1
28.03 bla 0
24.03 bla 0
24.03 bla 0

有人有什么想法吗?

推荐答案

use duplicated.如果重复记录,则返回 1 否则返回 0,因此 ! bang 运算符.+ 在逻辑之前将其转换为数字.

use duplicated. If duplicate records it returns 1 else 0, therefore ! bang operator. + before logical converts it to numeric.

df %>% mutate(drive = +!duplicated(paste(date, adress)))

    date adress drive
1  28.03    bla     1
2  28.03    xyz     1
3  17.03    abc     1
4  30.03    yxz     1
5  24.03    bla     1
6  17.03    abc     0
7  23.03    abc     1
8  28.03    bla     0
9  24.03    bla     0
10 24.03    bla     0

这篇关于如何在 R 的数据框中将第一个唯一记录标记(标记)为 1,其余类似的记录标记为 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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