[英]R - How to make a subset of columns based on values in a row in a data frame
[英]How to drop columns from data frame in R based on specified order of row values
我想知道如何根據指定的行值順序從 R 中的數據框中刪除列。
假設以下數據框:
df <- data.frame(a = c(1,6,2,5,2,0,9,3,21,15,4,0,5,2,1),
b = c(0,0,1,0,0,0,5,0,0,0,0,2,0,0,0),
c = c(1,1,1,1,0,0,0,0,0,10,10,10,10,10,0))
a b c
1 1 0 1
2 6 0 1
3 2 1 1
4 5 0 1
5 2 0 0
6 0 0 0
7 9 5 0
8 3 0 0
9 21 0 0
10 15 0 10
11 4 0 10
12 0 2 10
13 5 0 10
14 2 0 10
15 1 0 0
我現在想識別並刪除具有以下行值序列的任何列:0,任何其他值,0,0,0。 假設這個序列應該在一列中至少出現 3 次才能刪除該列。 因此,使用我的示例,我想實現以下目標:
a c
1 1 1
2 6 1
3 2 1
4 5 1
5 2 0
6 0 0
7 9 0
8 3 0
9 21 0
10 15 10
11 4 10
12 0 10
13 5 10
14 2 10
15 1 0
謝謝!
您可以使用“rollapply”類型 function 來檢查每個 window 的 5 個元素的條件,然后求和,看看您是否有例如 >= 3 個匹配項。
可以更改 window 寬度,5,(模式中的元素數)匹配數,3,或條件檢查 function my_condition
,具體取決於特定問題。
library(data.table) # for frollapply. or use library(zoo) and rollapply
my_condition <- function(x) all(x[c(1, 3:5)] == 0)
cond_match <-
sapply(df, function(x) sum(frollapply(x, 5, my_condition, fill = 0L)) >= 3)
df[cond_match == FALSE] # or if df is a data.table, df[, cond_match == FALSE, with = FALSE]
# a c
# 1 1 1
# 2 6 1
# 3 2 1
# 4 5 1
# 5 2 0
# 6 0 0
# 7 9 0
# 8 3 0
# 9 21 0
# 10 15 10
# 11 4 10
# 12 0 10
# 13 5 10
# 14 2 10
# 15 1 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.