【问题标题】:Finding columns in dataframe with specific number of values in R [duplicate]在R中查找具有特定数量值的数据框中的列[重复]
【发布时间】:2016-01-22 09:31:18
【问题描述】:

我有一个包含 3000 多列的数据框(data.table)。我需要找出我的数据框中只有 2 个和少于 2 个值的列。然后,我在提取具有 2 个和小于 2 个值的列之后,我想将它们从原始数据框中删除。 我说明如下: 原始数据框

Month   A       B         C
Jan-00  0.007   NA       1758.27
Feb-00  0.004   NA       1310.43
Mar-00  0.004   NA       1260.89
Apr-00  0.004   0.0002   1137.34
May-00  0.005   6.05E-05 1595.78
Jun-00  0.003   NA       4968.89
Jul-00  0.007   NA       NA
Aug-00  0.005   NA       NA
Sep-00  0.004   NA       NA

期望的输出

     Month    A         C
    Jan-00  0.007   1758.27
    Feb-00  0.004   1310.435
    Mar-00  0.004   1260.89
    Apr-00  0.004   1137.342105
    May-00  0.005   1595.78125
    Jun-00  0.003   4968.895238
    Jul-00  0.007   NA
    Aug-00  0.005   NA
    Sep-00  0.004   NA

感谢您在这方面的帮助。

【问题讨论】:

  • 最近stackoverflow.com/questions/34902809问了一个非常相似的问题后,你有没有自己尝试过?您是否在此过程中卡住了某个地方?
  • 使用dput提供示例数据也很有帮助。
  • @docendodiscimus 感谢您提供宝贵的信息。但是这个问题是基于多个条件的,而我的不是。我是这个软件的新手。
  • @mrub 从超过 3000 列和 180 行的数据框中提取示例,其中包含您想要呈现的场景有时可能有点困难。
  • @Aquarius 然后要么使用例如dput(db[1:5,1:5]) 或以其他人可以轻松导入的格式提供虚拟数据。

标签: r data.table multiple-columns


【解决方案1】:

我们可以使用Filter

Filter(function(x) sum(!is.na(x))>2, df1)
#   Month     A       C
#1 Jan-00 0.007 1758.27
#2 Feb-00 0.004 1310.43
#3 Mar-00 0.004 1260.89
#4 Apr-00 0.004 1137.34
#5 May-00 0.005 1595.78
#6 Jun-00 0.003 4968.89
#7 Jul-00 0.007      NA
#8 Aug-00 0.005      NA
#9 Sep-00 0.004      NA

或者

df1[colSums(!is.na(df1))>2]

如果数据集是data.table

 library(data.table)
 setDT(df1)[,unlist(df1[, lapply(.SD, function(x) 
                        sum(!is.na(x))>2)]), with=FALSE]

或者

 setDT(df1)[, Filter(function(x) sum(!is.na(x))>2, .SD)]

【讨论】:

  • 感谢您的回答并为重复道歉。你能告诉我我不能把它分集,例如df<-df1[,1:100]。它只给了我一个 1:100 没有行的向量。
  • @Aquarius 如果是data.table,则使用with=FALSE,即df1[, 1:100, with=FALSE]
  • 谢谢它有效。你能告诉我这with=FALSE部分代码的目的是什么吗?
  • @Aquarius 在?data.table中提到过,即A single column name, single expresson of column names, list() of expressions of column names, an expression or function call that evaluates to list (including data.frame and data.table which are lists, too), or (when with=FALSE) a vector of names or positions to select.
  • 你可以试试df2[,df2[, unlist(lapply(.SD, function(x) if(is.numeric(x)) sum(x, na.rm=TRUE)>0 else sum(!is.na(x))>0))],with=FALSE]data.table解决方案)
猜你喜欢
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 2019-08-05
  • 1970-01-01
  • 2019-02-26
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
相关资源
最近更新 更多