【问题标题】:Drop levels of a factor when droplevels() doesn't work in R当 droplevels() 在 R 中不起作用时,删除一个因子的级别
【发布时间】:2019-06-08 13:22:20
【问题描述】:

从我的data.frame D 中对变量tNULLs 的向量)进行子集化后,我得到了一个类因子对象。

我使用droplevels 删除级别并得到NULLs 的向量,我想知道为什么我仍然无法获得NULLs 的向量?

D <- read.csv("https://raw.githubusercontent.com/izeh/i/master/m.csv", h = T)

L <- split(D, D$study.name) ; L[[1]] <- NULL

t <- lapply(1:length(L), function(i) L[[i]]$t)

droplevels(t[[1]]) ## keep the vector of `NULL`s but drop the levels

## EXPECTED OUTPUT:
[[1]]
[1] NULL NULL NULL NULL NULL NULL

【问题讨论】:

  • 请添加预期输出

标签: r function loops subset


【解决方案1】:

在 R 中,NULL 对象是像 NA 一样的细节。这篇文章是一个非常好的解释:

repeat multiple NULL in R

要创建一个具有 NULL 值对象的空向量,这很难,因为它是一个长度为 0 的对象,也许你可以使用 NA 或使用其他解决方案:

D <- read.csv("https://raw.githubusercontent.com/izeh/i/master/m.csv", h = T)
L <- split(D, D$study.name)
L[[1]] <- NULL # NULL is 0 length, you cancel the first element of your list.

t <- lapply(1:length(L), function(i) L[[i]]$t) # Your try

# 2 solutions :
t <- lapply(1:length(L), function(i) rep(NA, length(L[[i]]$t))) # Replace with NA
t <- lapply(1:length(L), function(i) rep(list(NULL), length(L[[i]]$t))) # Replace with list of NULL 
: the result is a list of list with NULL

【讨论】:

  • 不幸的是,没有。但我尝试了不同的策略。但我真的很感谢你的回应。实际上,我赞成它。
  • 对不起,也许你不能有一个 NULL 向量的原因只是来自 NULL 长度为 0 的事实。所以你不能用 4 个 NULL 创建一个长度为 4 的向量,因为一个 NULL 是 0 长度。谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-23
  • 2012-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多