如何检查前一周的数据是否与 R 中的本周数据匹配

问题描述 投票:0回答:3

我在 R 中有一个数据框,其中包含一个具有特定字符串的列和获取数据的星期。如果本周的字符串与前一周的字符串匹配,我需要创建一个返回 0 或 1 的新列。

例如,尝试创建下面的“匹配”列。

感谢您的帮助!

Week     Data      Match
 1       Red         0
 2       Blue        0
 3       Blue        1
 4       Yellow      0
 5       Green       0
 6       Blue        0
 7       Blue        1
 8       Blue        1
 9       Green       0
 10      Yellow      0
r character
3个回答
0
投票

在包含非连续Weeks的稍微修改的数据集上,使用

diff
测量距离,使用
lag
测试匹配。

library(dplyr)

df %>% 
  mutate(Match = (if_else(c(0, diff(Week)) == 1, Data == lag(Data), FALSE))*1)
   Week   Data Match
1     1    Red     0
2     2   Blue     0
3     3   Blue     1
4     4 Yellow     0
5     6  Green     0
6     7   Blue     0
7     8   Blue     1
8    10   Blue     0
9    11  Green     0
10   12 Yellow     0

模组。数据

df <- structure(list(Week = c(1, 2, 3, 4, 6, 7, 8, 10, 11, 12), Data = c("Red", 
"Blue", "Blue", "Yellow", "Green", "Blue", "Blue", "Blue", "Green", 
"Yellow")), row.names = c(NA, -10L), class = "data.frame")

0
投票

您可以使用

lag()
包中的
dplyr
函数。然后,您可以使用另一个
ifelse
函数将第一个值替换为 0。

test <- data.frame(Week = 1:5, Data = c("Red", "Blue", "Blue", "Yellow", "Green"))

library(tidyverse)

test %>% 
  mutate(Match = ifelse(Data == lag(Data, default = "NA"), 1, 0))

 Week   Data Match
1    1    Red     0
2    2   Blue     0
3    3   Blue     1
4    4 Yellow     0
5    5  Green     0

根据@peter861222 对滞后函数中默认参数的建议进行编辑。


0
投票

在基地R:

df$Match <- c(0, tail(df$Data, -1) == head(df$Data, -1))
df
#>    Week   Data Match
#> 1     1    Red     0
#> 2     2   Blue     0
#> 3     3   Blue     1
#> 4     4 Yellow     0
#> 5     6  Green     0
#> 6     7   Blue     0
#> 7     8   Blue     1
#> 8    10   Blue     1
#> 9    11  Green     0
#> 10   12 Yellow     0
© www.soinside.com 2019 - 2024. All rights reserved.