R跨行比较列
我有以下问题,这对我来说是一个挑战,因为我或多或少是R的初学者 我有一个类似的data.frame,因此:R跨行比较列,r,compare,R,Compare,我有以下问题,这对我来说是一个挑战,因为我或多或少是R的初学者 我有一个类似的data.frame,因此: a b c 1 x g1 date1 2 x g1 date2 3 y g2 date3 4 y g3 date4 5 y g4 date5 6 z g1 date6 7 z g2 date7 8 x g4 date8 9 y g1 date9 10 y g3 date10 我想做的是将列a中的第一个值与第二个值进行比较。如果它们相同
a b c
1 x g1 date1
2 x g1 date2
3 y g2 date3
4 y g3 date4
5 y g4 date5
6 z g1 date6
7 z g2 date7
8 x g4 date8
9 y g1 date9
10 y g3 date10
我想做的是将列a
中的第一个值与第二个值进行比较。如果它们相同,则在b列中检查g2
是否在g1
之后
数据是按日期排序的,我基本上想找出g2
紧跟在g1
之后的出现次数,而a
列中的相应值是相似的
在示例中,上面的数据总和为1。(第6行和第7行)可能有一种更简单的方法,但这是我的
数据。表
library(data.table) ## v 1.9.6+
setDT(df)[a == shift(a, type = "lead") & b == "g1" & shift(b, type = "lead") == "g2", .N]
## [1] 1
这基本上是将a
与移位的a
列进行比较,同时检查b
列是否等于g1
,移位的b
列是否等于g2
。您将需要CRAN上最新的数据.表
版本,才能使其正常工作
使用dplyr
可以在这些行中找到一些内容
library(dplyr)
df %>%
filter(a == lead(a) & b == "g1" & lead(b) == "g2") %>%
count()
# Source: local data table [1 x 1]
#
# n
# (int)
# 1 1
还是用R基
sum(with(df, a == c(tail(as.character(a), -1), NA) & b == "g1" & c(tail(as.character(b), -1), NA) == "g2"))
## [1] 1
另一种选择:
数据:
及
你可以这样做
result <- NULL
for (i in 1:NROW(df)){result <- c(result, df$a[i]==df$a[i-1] & df$b[i]=="g2" & df$b[i-1]=="g1")}
length(which(result))
# [1] 1
结果
library(dplyr) #for lag
#df$a == lag(df$a) checks the equality in consecutive rows in a
#the rest of the code checks the order of g2 and g1 in consecutive rows
df$out <- df$a == lag(df$a) & grepl(paste('g2','g1'), paste(df$b, lag(df$b)))
> df
a b c out
1 x g1 date1 FALSE
2 x g1 date2 FALSE
3 y g2 date3 FALSE
4 y g3 date4 FALSE
5 y g4 date5 FALSE
6 z g1 date6 FALSE
7 z g2 date7 TRUE
8 x g4 date8 FALSE
9 y g1 date9 FALSE
10 y g3 date10 FALSE
sum(df$out)
[1] 1
result <- NULL
for (i in 1:NROW(df)){result <- c(result, df$a[i]==df$a[i-1] & df$b[i]=="g2" & df$b[i-1]=="g1")}
length(which(result))
# [1] 1
a <- c("x", "x", "y", "y", "y", "z", "z", "x", "y", "y")
b <- c("g1", "g1", "g2", "g3", "g4", "g1", "g2", "g4", "g1", "g3")
c <- paste("date", 1:10, sep = "")
df <- as.data.frame(cbind(a,b,c))