【问题标题】:Subset data frames inside of a list based on column classes基于列类的列表内的子集数据框
【发布时间】:2015-08-09 23:28:48
【问题描述】:

我有一个由数据框组成的非常大的列表,列表中的每个元素都是一个不同的数据框,其中每一列由不同类型的变量和不同长度的数据框组成。我想对这个列表中的数据框进行子集化,并且只保留那些具有“整数”或“数字”类的列,同时保持数据框结构(所以看起来没有“lapply”)。

MRE 如下:

 x1 <- c(1,2,3,4)
y1 <- c(letters[1:4])
z1 <- as.integer(c(0, 1, 0, 1))
df1 <- data.frame(x1,y1,z1)
str(df1)

x2 <- c(0, 1, 2, 3,4 )
y2 <- as.integer(c(0, 1, 0, 1, 0))
z2 <- c(letters[1:5])
df2 <- data.frame(x2,y2,z2)
str(df2)

list12 <- list(df1, df2)
str(list12)

#the following have not worked or returned errors:
#list12<- sapply(list12, function (x) subset(x, select = class %in%        c('character', 'factor'), drop =FALSE))
#Error in match(x, table, nomatch = 0L) : 
#  'match' requires vector arguments 

#list12 <- list12[sapply(list12, function(x) subset(x, select x %in% class is.numeric(x) || is.integer(x))]
#unexpected symbol

#list12 <- list12[, sapply(list12, function(x) is.numeric(x) || is.integer(x))]
#  incorrect number of dimensions

#list12 <- sapply(list12, function(x) subset(x, select = class is.numeric(x) || is.integer(x))
#unexpected symbol

我的预期结果是 2 个数据框的列表,其中只有包含整数或数字类的列

【问题讨论】:

    标签: r list dataframe subset


    【解决方案1】:

    我喜欢大卫的回答 (+1),但使用 sapply() 对我来说感觉更自然。

    lapply(list12, function(x) x[sapply(x, is.numeric)])
    

    【讨论】:

      【解决方案2】:

      另一种选择是在lapply 中使用Filter

      lapply(list12, Filter, f = is.numeric)
      # [[1]]
      #   x1 z1
      # 1  1  0
      # 2  2  1
      # 3  3  0
      # 4  4  1
      # 
      # [[2]]
      #   x2 y2
      # 1  0  0
      # 2  1  1
      # 3  2  0
      # 4  3  1
      # 5  4  0
      

      【讨论】:

      • 对于Filter的介绍,加一个。
      【解决方案3】:

      试试吧:

      lapply(list12,function(x) x[vapply(x,class,"") %in% c("integer","numeric")])
      

      【讨论】:

      • 不需要指定类,is.numeric 两者都有。
      猜你喜欢
      • 2021-04-25
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 1970-01-01
      相关资源
      最近更新 更多