首页 文章

基于列类的列表内的子集数据帧

提问于
浏览
4

我有一个由数据帧组成的非常大的列表,列表的每个元素都是不同的数据帧,其中每列由不同类型的变量和不同长度的数据帧组成 . 我想在这个列表中对数据帧进行子集化,并且只保留那些列具有“整数”或“数字”类,同时保持数据帧结构(所以看似没有“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个数据框的列表,只有包含整数或数字类的列

3 回答

  • 1

    另一种选择是在 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
    
  • 3

    试一试:

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

    我喜欢David的回答(1),但使用 sapply() 对我来说更自然 .

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

相关问题