R 基于列类的列表中的子集数据帧

R 基于列类的列表中的子集数据帧,r,list,dataframe,subset,R,List,Dataframe,Subset,我有一个由数据帧组成的非常大的列表,列表中的每个元素都是不同的数据帧,其中每个列都由不同类型的变量和不同长度的数据帧组成。我想将此列表中的数据帧子集,只保留那些类为“integer”或“numeric”的列,同时保留数据帧结构(因此看起来没有“lappy”) 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)

我有一个由数据帧组成的非常大的列表,列表中的每个元素都是不同的数据帧,其中每个列都由不同类型的变量和不同长度的数据帧组成。我想将此列表中的数据帧子集,只保留那些类为“integer”或“numeric”的列,同时保留数据帧结构(因此看起来没有“lappy”)

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
x1试试看:

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

另一个选项是在
lappy

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
我喜欢大卫的答案(+1),但使用
sapply()
对我来说更自然

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

无需指定类,
是。数值
捕获了这两个类。对于
过滤器的介绍,加上一个。