簡體   English   中英

Basic R:使用邏輯向量按列對DF進行子集

[英]Basic R: Subsetting DF by Columns with Logical Vector

我有一個數據框trainSmall ,有六列。

> trainSmall
     chr      pos      end LCR gc.50  type
  1:  22 39491638 39491639   0     0 del_L
  2:  22 29434028 29434029   0     0   ins
  3:  22 28347247 28347248   0     0 del_R
  4:  22 40121931 40121932   0     0   ins
  5:  22 39122351 39122352   0     0 del_L
 ---                                      
768:  22 27869380 27869381   0     0 del_R
769:  22 28823159 28823160   0     0   ins
770:  22 24319557 24319558   0     0 del_R
771:  22 38570330 38570331   0     0 del_L
772:  22 48182139 48182140   0     0 del_L
> is.data.frame(trainSmall)
[1] TRUE

我還有一個向量excl ,其中包含四個項目。

> excl
[1] "chr"  "pos"  "end"  "type"

我想借的所有行trainSmall ,但僅列 excl 所以我嘗試了

> trainSmall[, !colnames(trainSmall) %in% excl]
[1] FALSE FALSE FALSE  TRUE  TRUE FALSE

但這只是給我另一個邏輯矢量,而不是數據幀中的實際行。

即使在做

> trainSmall[, c(F,F,F,T,T,F)]
[1] FALSE FALSE FALSE  TRUE  TRUE FALSE

不能按我預期的那樣工作。

我很困惑,因為這似乎是很多地方(例如此答案 )提倡的用於設置數據幀的方法。 我究竟做錯了什么?

對可能的重復標志的響應 :在這種情況下,似乎沒有解決方案。

> trainSmall[, -which(names(trainSmall) %in% excl)]
[1] -1 -2 -3 -6
> trainSmall[ , !names(trainSmall) %in% excl]
[1] FALSE FALSE FALSE  TRUE  TRUE FALSE

你可以去(注意括號):

df[, !(colnames(df) %in% excl)]

另一種有趣的方式是自己動手操作(與%in%相反):

excl <- c("chr", "pos", "end", "type")

'%!in%' <- function(x,y)!('%in%'(x,y))
mask <- colnames(df) %!in% excl
df[,mask]

兩者都會產生

   LCR gc.50
1:   0     0
2:   0     0
3:   0     0
4:   0     0
5:   0     0

給定代碼的輸出,我認為您的數據采用data.table格式(數據表同時具有數據框架和數據表作為其類)。 因此,這應該工作:

trainSmall[, !excl, with = FALSE]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM