【问题标题】:Subset rows based on values of columns of unknown names and number of columns基于未知名称列的值和列数的子集行
【发布时间】:2011-09-29 23:10:13
【问题描述】:

我确定我有一个非常基本的问题,但是在寻找有关如何完成某些数据框/矩阵的子集(获取行号)的想法后,我感到很沮丧,这些数据框/矩阵可以有任意数量的列,并且列名会更改所有时间。我只想查找数据框中任何列大于 0 的行(索引)。由于列名和列数未知,我不知道该怎么做...

一个例子:

# these are the terms I am looking in
terms <- c("beats", "revs", "revenue", "earnings")
# dict <- Dictionary(terms)
# dictStudy <- inspect(DocumentTermMatrix(mydata.corpus.tmp, list(dictionary = dict)))

dictStudy <- data.frame(beats=c(0, 0, 0, 1, 0, 2), revs=c(0, 0, 0, 1, 0, 1), revenue=c(0, 0, 0, 0, 0, 0), earnings=c(1, 0, 0, 1, 0, 1)) 
ss <- expression(terms > 0)
dictStudy.matching <- subset(dictStudy, eval(ss))

我希望表达式和 eval 能救我,但我想不通。

如何在数据框中仅查找任何列 > 0 的行?

【问题讨论】:

    标签: r


    【解决方案1】:

    我假设您的意思是您想要该行的至少一个元素大于零的行(即任何列都大于零)。

    > which(apply(dictStudy,1,function(x) any(x > 0)))
    [1] 1 4 6
    

    正如 Tommy 在下面指出的那样,这假设您的所有列实际上都是数字的。您可以通过对数据框进行子集化以仅提取那些数字列来回避这一点:

    > which(apply(dictStudy[,sapply(dictStudy,is.numeric)],1,function(x) any(x > 0)))
    [1] 1 4 6
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-02
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 2013-06-09
      相关资源
      最近更新 更多