用R中相同的值索引出下一行 [英] Index out the subsequent row with an identical value in R

查看:59
本文介绍了用R中相同的值索引出下一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下名为test的矩阵:

            High Thresh Sig
2007-02-27 19.01  11.88   1
2007-03-01 19.40  17.29   1
2007-03-02 18.63  17.29   1
2007-03-14 21.25  20.41   1
2007-06-25 17.24  16.70   1
2007-06-27 18.98  18.89   1

我想舍弃2007年3月2日的行,因为该行在Thresh列中的值与前一天相同.

I would like to discard the row on 2007-03-02 because it has an identical value in the Thresh column as the preceding day.

我尝试过:

test_shorter <- subset(test, diff(Thresh) !=0)

但是它索引出第一次出现,而我想丢弃第二次出现.

but it indexes out the first occurrence whereas I want to discard the second occurrence.

推荐答案

duplicated函数非常适合此类情况.例如:

The duplicated function is great for situations like this. For example:

> test[!duplicated(test[,'Thresh']),]
            High Thresh Sig
2007-02-27 19.01  11.88   1
2007-03-01 19.40  17.29   1
2007-03-14 21.25  20.41   1
2007-06-25 17.24  16.70   1
2007-06-27 18.98  18.89   1

如果您希望获得与尝试的结果相同的结果,则可以使用fromLast=参数:

If you wanted the same results as what you tried, you can use the fromLast= argument:

> test[!duplicated(test[,'Thresh'], fromLast=TRUE),]
            High Thresh Sig
2007-02-27 19.01  11.88   1
2007-03-02 18.63  17.29   1
2007-03-14 21.25  20.41   1
2007-06-25 17.24  16.70   1
2007-06-27 18.98  18.89   1

这篇关于用R中相同的值索引出下一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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