从R中的data.frame中删除整列

有谁知道如何从R中的data.frame中删除整个列?例如,如果我得到此data.frame:


> head(data)

   chr       genome region

1 chr1 hg19_refGene    CDS

2 chr1 hg19_refGene   exon

3 chr1 hg19_refGene    CDS

4 chr1 hg19_refGene   exon

5 chr1 hg19_refGene    CDS

6 chr1 hg19_refGene   exon

我想删除第二列。


翻翻过去那场雪
浏览 3939回答 3
3回答

泛舟湖上清波郎朗

您可以将其设置为NULL。> Data$genome <- NULL> head(Data)&nbsp; &nbsp;chr region1 chr1&nbsp; &nbsp; CDS2 chr1&nbsp; &nbsp;exon3 chr1&nbsp; &nbsp; CDS4 chr1&nbsp; &nbsp;exon5 chr1&nbsp; &nbsp; CDS6 chr1&nbsp; &nbsp;exon正如评论中指出的那样,这里还有其他一些可能性:Data[2] <- NULL&nbsp; &nbsp; # Wojciech SobalaData[[2]] <- NULL&nbsp; # same as aboveData <- Data[,-2]&nbsp; # Ian FellowsData <- Data[-2]&nbsp; &nbsp;# same as above您可以通过以下方式删除多列:Data[1:2] <- list(NULL)&nbsp; # MarekData[1:2] <- NULL&nbsp; &nbsp; &nbsp; &nbsp; # does not work!但是,请谨慎使用矩阵子集,因为您可能会得到一个向量:Data <- Data[,-(2:3)]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# vectorData <- Data[,-(2:3),drop=FALSE]&nbsp; # still a data.frame

慕后森

使用data.frames 时,发布的答案非常好。但是,从内存角度来看,这些任务的效率可能非常低。对于大数据,删除列可能会花费异常长的时间和/或由于out of memory错误而失败。软件包data.table可帮助:=操作员解决此问题:library(data.table)> dt <- data.table(a = 1, b = 1, c = 1)> dt[,a:=NULL]&nbsp; &nbsp; &nbsp;b c[1,] 1 1我应该举一个更大的例子来说明差异。我将在某个时候更新此答案。
打开App,查看更多内容
随时随地看视频慕课网APP