2015-05-27 182 views
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

另一個選項是在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 
+1

有關'Filter'的介紹,請加上一個。 –

1

列,只要嘗試:

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

沒有必要指定類,'is.numeric'同時捕獲這兩個類。 –

1

我喜歡David的回答(+1),但是使用sapply()對我來說更自然。

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