Reputation: 3126
library(tidyverse)
data(mtcars)
mtcars <- rownames_to_column(mtcars,var = "car")
mtcars$id <- c(1:length(mtcars$car))
mtcars$make <- map_chr(mtcars$car,~strsplit(.x," ")[[1]][1])
mt2 <- mtcars %>% select(1:4,id,make) %>% nest(-make,.key = "l")
mt4 <- mt2[1:5,]
mt5 <- mt2[1:5,]
`
Now - I´d like to have the listcolumn for mazda set to NULL.
mt4[mt4$make=="Mazda","l"]<-NULL
However, comparing mt4$l
to mt5$l
I find that the "mazda" elements have been removed, but that the other elements have been shifted upward.
Could someone explain why this is logical?
How can I selectively only NULL a certain element within a listcolumn?
Upvotes: 2
Views: 51
Reputation: 160607
Please include non-base packages in your questions. In this case, we need:
library(dplyr)
library(purrr)
library(tidyr)
library(tibble)
(or just library(tidyverse)
, I believe).
By assigning NULL
like that to an element, you are telling R to remove that element from the list, thereby making it shorter. If you want to replace the element with a NULL
element, try
mt4[mt4$make=="Mazda","l"] <- list(list(NULL))
instead. (This happens to also work if the conditional mt4$make=="Mazda"
were to return multiple matches; obviously not a factor with this example, but good to know.)
Upvotes: 3