gpt4 book ai didi

R删除列表元素的行并保留行名

转载 作者:行者123 更新时间:2023-12-04 10:39:12 25 4
gpt4 key购买 nike

我有一个包含空单元格的数据框,我将其拆分为一个列表:

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) }

但是,当我从列表的一个元素中删除空行时,该元素的行名将被删除:

list[[1]] <- list[[1]][list[[1]] != "",]
rownames(list[[1]])
NULL

如何防止这种情况发生?

最佳答案

行名称被“删除”,因为您将数据框转换为矢量(根据定义,它没有行名称)。

当您尝试对仅包含一列的 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"

drop

logical. If TRUE the result is coerced to the lowest possible dimension. The default is to drop if only one column is left, but not to drop if only one row is left.

关于R删除列表元素的行并保留行名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27470193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com