我想根據某些條件刪除列。如何根據某些條件刪除列?
library(data.table)
dt <- data.table(1:4, rep(TRUE, 4), c(TRUE, FALSE, TRUE, TRUE))
在這種情況下,我想刪除全部TRUE
列。輸出應該是
# V1 V3
# 1 TRUE
# 2 FALSE
# 3 TRUE
# 4 TRUE
我想根據某些條件刪除列。如何根據某些條件刪除列?
library(data.table)
dt <- data.table(1:4, rep(TRUE, 4), c(TRUE, FALSE, TRUE, TRUE))
在這種情況下,我想刪除全部TRUE
列。輸出應該是
# V1 V3
# 1 TRUE
# 2 FALSE
# 3 TRUE
# 4 TRUE
您可以使用子集
dt[,!sapply(dt, function(x) all(x==TRUE)), with=FALSE]
這裏sapply(dt, function(x) all(x==TRUE))
部分發現,其中所有的值都是TRUE的列從選擇中排除。然後我們否定它,並使用with=FALSE
(因爲這是一個data.table,而不是一個data.frame)
Filter()
是用於說明根據特定功能是否評估爲TRUE選擇一個數據幀的列的有用的功能。你的情況:
Filter(function(x) !all(x == TRUE), dt)
V1 V3
1: 1 TRUE
2: 2 FALSE
3: 3 TRUE
4: 4 TRUE
只是'sapply(dt,all)'會起作用嗎? – thelatemail