如何在 data.frame 中找到元素的第一次和最后一次出现? [英] How can I find the first and last occurrences of an element in a data.frame?

查看:22
本文介绍了如何在 data.frame 中找到元素的第一次和最后一次出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经彻底搜索了 FIRST 的直接 R 翻译.最后.SAS DATA 步骤中的指针,但似乎找不到.对于那些不熟悉 SAS 的人,首先.是一个布尔值,用于标识给定元素在表中的第一次出现和最后一次出现.是一个布尔值,用于标识最后一次出现.例如,考虑以下排序表:

I have searched exhaustively for a direct R translation for the FIRST. and LAST. pointers in SAS DATA steps but can't seem to find one. For those not familiar with SAS, FIRST. is a boolean that identifies the first appearance of a given element in a table and LAST. is a boolean that identifies the last appearance. For instance, consider the following sorted table:

V1    V2    V3
1     1     1
1     1     2
1     2     3
1     2     4
2     3     5
2     3     6
2     4     7
2     4     8
3     5     9
3     5     10
3     6     11
3     6     12

因为 SAS DATA 步骤逐行读取表格,所以我可以使用如下语句:

Because SAS DATA steps read tables line by line, I can use a statement like:

IF FIRST.V1 THEN DO ...

当且仅当这是第一次在 V1 中遇到观察时,FIRST.V1 才会返回 TRUE.换句话说,对于 V1[1]('1' 的第一次出现)、V1[5]('2' 的第一次出现)和 V1[9]('3' 的第一次出现),它将返回 true).最后.指针以类似的方式起作用,但具有该元素的最终外观.

FIRST.V1 will return TRUE if and only if this is the first time the observation has been encountered in V1. In other words, it will return true for V1[1] (the first appearance of '1'), V1[5] (the first appearance of '2'), and V1[9] (the first appearance of '3'). The LAST. pointer functions in analogous fashion, but with the final appearance of that element.

R 中是否有任何类似的东西?

Is there anything in R that emulates this?

推荐答案

您可以使用 duplicated 和 rev (for LAST):

You can do this with duplicated and rev (for LAST):

> v1=c(1,1,1,2,2,3,3,3,3,4,4,5)

> data.frame(v1,FIRST=!duplicated(v1),LAST=rev(!duplicated(rev(v1))))
   v1 FIRST  LAST
1   1  TRUE FALSE
2   1 FALSE FALSE
3   1 FALSE  TRUE
4   2  TRUE FALSE
5   2 FALSE  TRUE
6   3  TRUE FALSE
7   3 FALSE FALSE
8   3 FALSE FALSE
9   3 FALSE  TRUE
10  4  TRUE FALSE
11  4 FALSE  TRUE
12  5  TRUE  TRUE

这篇关于如何在 data.frame 中找到元素的第一次和最后一次出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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