[英]Return rows where consecutive values meet criterion
我有以下數據幀df
。 我想返回一個向量result
,指示哪些行符合以下標准:該行中至少有2個連續值低於-1.7。
set.seed(123)
df <- data.frame(V1=rnorm(10,-1.5,.5),
V2=rnorm(10,-1.5,.5),
V3=rnorm(10,-1.5,.5),
V4=rnorm(10,-1.5,.5),
V5=rnorm(10,-1.5,.5),
V6=rnorm(10,-1.5,.5),
V7=rnorm(10,-1.5,.5),
V8=rnorm(10,-1.5,.5),
V9=rnorm(10,-1.5,.5),
V10=rnorm(10,-1.5,.5))
rownames(df) <- c(seq(1976,1985,1))
結果將是一個向量:
result <- c(1977,1979,1980,1982,1983,1985)
一個選項是使用apply
遍歷行,使用rle
創建邏輯條件,檢查是否有any
lengths
大於1的TRUE元素,提取names
names(which(apply(df, 1, function(x) with(rle(x < - 1.7), any(lengths[values] > 1)))))
#[1] "1977" "1979" "1980" "1982" "1983" "1985"
或者更好的方法是通過放置兩個邏輯矩陣來對其進行矢量化(即刪除數據集的第一列,檢查它是否小於-1.7,同樣刪除最后一列並執行相同操作), Reduce
其Reduce
為單個邏輯matrix
通過檢查相應元素是否為TRUE
,獲取rowSums
,如果值大於0,則提取行名稱
names(which(rowSums(Reduce(`&`, list(df[-ncol(df)] < -1.7, df[-1] < -1.7))) > 0))
#[1] "1977" "1979" "1980" "1982" "1983" "1985"
一個有趣的選項which
使用arr.ind = TRUE
temp <- which(df < -1.7, arr.ind = TRUE)
rownames(df)[aggregate(col~row, temp, function(x) any(diff(x) == 1))[, 2]]
#[1] "1977" "1979" "1980" "1982" "1983" "1985"
我們首先獲得值小於-1.7的所有行和列位置。 使用aggregate
我們為每一row
組合col
,並檢查row
是否至少有一個連續值,以及返回其rownames
TRUE
子集的值。
一種解決方案,它使用滯后和來獲得向量中每對數字的總和。 如果滯后總和為2,則表示該行中至少有2個連續值滿足條件。
rownames(df)[apply(df < -1.7, 1, function(x) any(x[-nrow(df)] + x[-1] == 2))]
# [1] "1977" "1979" "1980" "1982" "1983" "1985"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.