If you replace an element of an list with NULL, it shortens the list.

Well, sometimes.

> a = list(1, 2, 3, 4, 5)
> b = list(8, NULL, 10)
> length(a)
[1] 5
> a[2:4] = b
> length(a)
[1] 5
> a
[[1]]
[1] 1

[[2]]
[1] 8

[[3]]
NULL

[[4]]
[1] 10

[[5]]
[1] 5

> a[3] = NULL
> length(a)
[1] 4

@data_science

@peterdrake Assigning NULL is the way you delete something in a list (like a column from a data frame)
> mtcars <- mtcars
> ncol(mtcars)
[1] 11
> mtcars$mpg <- NULL
> ncol(mtcars)
[1] 10

If you want to keep the length, you should assign NULL as a list.
> rm(mtcars)
> mtcars <- mtcars
> ncol(mtcars)
[1] 11
> mtcars$mpg <- list(NULL)
> ncol(mtcars)
[1] 11

Follow

@hhmacedo Yeah, I got that. It just strikes me as odd that these things behave differently. I would expect

v[1:3] <- list(1, NULL, 3)

to behave just like:

v[1] <- 1
v[2] <- NULL
v[3] <- 3

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.