我有一个带有空单元格的数据框,我将其拆分为一个列表:
df <- data.frame(c("q","w","","r","t","y"),c("a","b","","d","e","f"),c("x","c","v","b","","m"))
colnames(df) <- c("qwerty","abc","bnm")
rownames(df) <- c("1a","1b","1c","1d","1e","1f")
list <- lapply(df, as.data.frame)
for(i in 1:length(list)){ rownames(list[[i]]) <- rownames(df) }
但是,当我从列表的某个元素中删除空行时,会删除该元素的rownames:
list[[1]] <- list[[1]][list[[1]] != "",]
rownames(list[[1]])
NULL
如何防止这种情况发生?
答案 0 :(得分:6)
行名称被“删除”,因为您将数据框转换为向量(根据定义没有行名)。
当您尝试对仅包含一列的data.frame
进行子集时,会发生这种情况。为了防止这种情况,请使用drop = FALSE
,如下所示:
lapply(list, function(x) x[x != "",, drop = FALSE])
# $qwerty
# X[[1L]]
# 1a q
# 1b w
# 1d r
# 1e t
# 1f y
#
# $abc
# X[[2L]]
# 1a a
# 1b b
# 1d d
# 1e e
# 1f f
#
# $bnm
# X[[3L]]
# 1a x
# 1b c
# 1c v
# 1d b
# 1f m
为了说明这一点,请考虑以下示例
df <- data.frame(A = c("a", "", "b"))
(subdf <- df[df$A != "", ])
# [1] a b
# Levels: a b
class(subdf)
# [1] "factor"
rownames(subdf)
# NULL
有关详细信息,请参阅?"[.data.frame"
下拉强>
逻辑。如果为TRUE,则结果强制为尽可能低 尺寸。 默认情况下,如果只剩下一列,则会丢弃,但不会 如果只剩下一行就丢弃。