识别R data.frame列中值的变化位置 [英] Identifying where value changes in R data.frame column
本文介绍了识别R data.frame列中值的变化位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在R中有一个 data.frame
,其中 value
列包含类<$ c $的数据c>字符。我想确定 value
发生变化的行号。在下面的示例中,我想得出4、7和9。有没有办法做到这一点而不循环?
I have a data.frame
in R where the value
column contains data of the class character
. I want to identify the row numbers where value
changes. In the example below I want to get out 4, 7, and 9. Is there a way to do this without looping?
df <- data.frame(ind=1:10,
value=as.character(c(100,100,100,200,200,200,300,300,400,400)),
stringsAsFactors=F)
df
ind value
1 1 100
2 2 100
3 3 100
4 4 200
5 5 200
6 6 200
7 7 300
8 8 300
9 9 400
10 10 400
推荐答案
一个简单的解决方案是在dplyr中使用lag函数:
A simple solution is to use the lag function in dplyr:
which(df$value != dplyr::lag(df$value))
这篇关于识别R data.frame列中值的变化位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文