简体   繁体   中英

Drop levels of a factor when droplevels() doesn't work in R

After subsetting variable t (which is a vector of NULL s) from my data.frame D , I get an object of class factor.

I use droplevels to drop the levels and get a vector of NULL s, I was wondering why I can't still achieve a vector of NULL s?

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

In R, NULL objects are specifics like NA. This post is a really good explanation :

repeat multiple NULL in R

To create an empty vector with NULL value object, it is hard because it is a 0 length object, maybe you could use NA or use the other solution :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM