ncss-tech / aqp

Algorithms for Quantitative Pedology
http://ncss-tech.github.io/aqp/
54 stars 15 forks source link

`split()`: allow `NA`->`"<missing>"` levels #282

Closed brownag closed 1 year ago

brownag commented 1 year ago

split() allows NA levels (and preserves them as "<missing>" when drop=FALSE)

library(aqp)
#> This is aqp 2.0
data("jacobs2000")
site(jacobs2000)$grp1 <- c(1, 1, 1, 2, 2, NA, NA)
site(jacobs2000)$grp2 <- c(1, 2, 1, 2, 1, 2, 1)

# no more error
x <- split(jacobs2000, jacobs2000$grp1)
length(x)
#> [1] 2

# additional "<missing>" group
x <- split(jacobs2000, "grp1", drop = FALSE)
#> converting grp1 to factor
length(x)
#> [1] 3
length(x[["<missing>"]])
#> [1] 2

# interaction 
x <- split(jacobs2000, list(jacobs2000$grp1, jacobs2000$grp2))
length(x)
#> [1] 4

# interaction (with drop=FALSE)
x <- split(jacobs2000, list(jacobs2000$grp1, jacobs2000$grp2), drop = FALSE)
length(x)
#> [1] 6
names(x)
#> [1] "<missing>.1" "1.1"         "2.1"         "<missing>.2" "1.2"        
#> [6] "2.2"

# interaction (with factor with unused levels and drop=FALSE)
jacobs2000$grp3 <- factor(jacobs2000$grp2, levels = 1:10)
x <- split(jacobs2000, list(jacobs2000$grp1, jacobs2000$grp3), drop = FALSE)
length(x)
#> [1] 30
dylanbeaudette commented 1 year ago

Good idea, thanks. Looks good to me.