无法从数据框中删除列,输出变成逻辑向量

Can't remove columns from a dataframe, output turns into a logical vector

我从 cSplit 函数中得到的 data.frame 似乎有问题。

如果没有 NAs,我无法使用以下代码提取列:

data_places <- data_table[ , colSums(is.na(data_table)) == 0 ]

输出是一个 Named logi 向量而不是一个 data.frame 向量,它没有包含具有 NA 的行的列。

问题主要是由于 splitstackshape 包的 cSplit 函数的 data.frame 输出。使用 data.table 包也会出现此问题。

我尝试创建一个新的 data.frame 来提取 cSplit 函数的 data.frame 输出的列,上面的代码工作正常。

知道 cSplitdata.frame 输出有什么问题吗?

这是我的代码示例:

library(splitstackshape)
data <- data.frame(V1=c("Place1-Place1-Place1-Place1-Place3-Place5",
          "Place1-Place4-Place2-Place3-Place3-Place5-Place5",
          "Place6-Place6",
          "Place1-Place2-Place3-Place4"))

data_table <- cSplit(data, "V1", sep="-", direction = "wide")
data_places <- data_table[ , colSums(is.na(data_table)) == 0 ]
data_places
str(data_places)

我们需要使用 with=FALSE,因为 cSplit 的输出是一个 data.table 对象。

data_table[ , colSums(is.na(data_table)) == 0 , with=FALSE]
#      V1_1   V1_2
#1: Place1 Place1
#2: Place1 Place4
#3: Place6 Place6
#4: Place1 Place2

如果我们看 ?data.table

with - By default with=TRUE and j is evaluated within the frame of x; column names can be used as variables. When with=FALSE j is a character vector of column names or a numeric vector of column positions to select, and the value returned is always a data.table. with=FALSE is often useful in data.table to select columns dynamically.


另一种选择是使用 Filter

Filter(function(x) all(!is.na(x)), data_table)