[英]R - Test if value is the same as the one in the cell above
I have the following df: 我有以下df:
name color
A red
B red
C green
D red
E red
F red
And I want to test the values in the 'color' column to see if they're the same as the values in the row above and write to a new column... I can do so using the following: 我想测试“颜色”列中的值,看它们是否与上一行中的值相同,然后写入新列...我可以使用以下方法进行操作:
> df$same <- ifelse(df$color == df$color[c(NA,1:(nrow(df)-1))], 1, 0)
To give me: 给我:
name color same
A red NA
B red 1
C green 0
D red 0
E red 1
F red 1
But is there a cleaner way to do it? 但是,有没有更清洁的方法呢? (I use this all the time)...
(我经常用这个)...
You can try the lag
function from dplyr
package. 您可以尝试使用
dplyr
软件包中的lag
功能。 You can create a new column with the values of the row above and after compare them, 您可以使用上面一行的值创建一个新列,然后将它们进行比较,
> dt$color_above <- lag(dt$color, n=1)
> dt
name color color_above
1 A red <NA>
2 B red red
3 C green red
4 D red green
5 E red red
6 F red red
Or solve the issue directly, you can use the pipe-operators from magrittr
package. 或者直接解决问题,您可以使用
magrittr
软件包中的管道操作magrittr
。 It is still verbose, but i think it keeps the code more clear. 它仍然很冗长,但是我认为它使代码更清晰。
> dt %$%
{ color == lag(color, n=1) } %>%
as.numeric() %>%
{.} -> dt$same
> dt
name color same
1 A red NA
2 B red 1
3 C green 0
4 D red 0
5 E red 1
6 F red 1
Adding to Rafael's answer, you can use ifelse
with dplyr::mutate
: 添加到Rafael的答案中,可以将
ifelse
与dplyr::mutate
:
> dt <- data_frame(name = c('A', 'B', 'C', 'D', 'E', 'F'), color = c('red', 'red', 'green', 'red', 'red', 'red'))
> dt
# A tibble: 6 x 2
name color
<chr> <chr>
1 A red
2 B red
3 C green
4 D red
5 E red
6 F red
> dt %>% mutate(same = ifelse(color == lag(color), 1, 0))
# A tibble: 6 x 3
name color same
<chr> <chr> <dbl>
1 A red NA
2 B red 1
3 C green 0
4 D red 0
5 E red 1
6 F red 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.