我有以下data.frame
:
data_1 <- structure(list(Line = structure(1:4, .Label = c("K1", "K2", "K3",
"K4"), class = "factor"), A = c(4L, 1L, -1L, 2L), B = c(3L, -2L,
-1L, 4L), C = c(-1L, 1L, 2L, 5L), D = c(2L, -5L, 3L, -7L), E = c(4L,
1L, 4L, 9L)), class = "data.frame", row.names = c(NA, -4L))
我要删除integer
列。我尝试:
rapply(object = data_1, classes = 'integer', how = 'list', f = function(x) {
x <- NULL
})
和
lapply(X = data_1, FUN = function(x) {
Filter(f = is.integer, x = x) <- NULL
})
但是不起作用。
我还需要这样做以获取列表:
list_1 <- list(data_1 = structure(list(Line = structure(1:4, .Label = c("K1",
"K2", "K3", "K4"), class = "factor"), A = c(4L, 1L, -1L, 2L),
B = c(3L, -2L, -1L, 4L), C = c(-1L, 1L, 2L, 5L), D = c(2L,
-5L, 3L, -7L), E = c(4L, 1L, 4L, 9L)), class = "data.frame", row.names = c(NA,
-4L)), data_2 = structure(list(Line = structure(1:4, .Label = c("K1",
"K2", "K3", "K4"), class = "factor"), A = c(4L, 1L, -1L, 2L),
B = c(3L, -2L, -1L, 4L), C = c(-1L, 1L, 2L, 5L), D = c(2L,
-5L, 3L, -7L), E = c(4L, 1L, 4L, 9L)), class = "data.frame", row.names = c(NA,
-4L)), data_3 = structure(list(Line = structure(1:4, .Label = c("K1",
"K2", "K3", "K4"), class = "factor"), A = c(4L, 1L, -1L, 2L),
B = c(3L, -2L, -1L, 4L), C = c(-1L, 1L, 2L, 5L), D = c(2L,
-5L, 3L, -7L), E = c(4L, 1L, 4L, 9L)), class = "data.frame", row.names = c(NA,
-4L)))
我尝试:
rapply(object = list_1, classes = 'integer', how = 'list', f = function(x) {
rapply(x, rm(x))
})
lapply(X = list_1, FUN = function(x) {
lapply(X = Filter(is.integer, x), rm(x))
})
但是,也不起作用。
期望输出:
Line
1 K1
2 K2
3 K3
4 K4
我只需要使用R base
的解决方案,而不需要其他软件包(使用dplyr
和您的_if
函数)。
答案 0 :(得分:0)
这是使用lapply
的R基本解决方案:
myfun <- function(df){
idx <- sapply(seq_len(ncol(df)), function(x) class(df[,x])) != "integer"
df[, idx]
}
lapply(list_1, myfun)