@@ -557,6 +557,17 @@ setMethod("subsetHz", signature(x = "SoilProfileCollection"), function(x, ..., d
557557 x
558558})
559559
560+ # produces an "all NA" data.frame with n rows, based on schema of x
561+ .create_placeholder_df <- function (x , n , as.class = " data.frame" ) {
562+ if (n == 0 ) {
563+ return (x [0 , ])
564+ }
565+ template <- as.data.frame(x [1 , , drop = FALSE ])
566+ template [seq_len(n ), ] <- NA
567+ rownames(template ) <- NULL
568+ .as.data.frame.aqp(template , as.class )
569+ }
570+
560571# ' @description used to implement "drop=FALSE" for various methods that remove horizons from SoilProfileCollection object
561572# ' @noRd
562573.insert_dropped_horizons <- function (object = SoilProfileCollection(),
@@ -572,22 +583,23 @@ setMethod("subsetHz", signature(x = "SoilProfileCollection"), function(x, ..., d
572583 newid <- sites [[pid ]][which(sites [[pid ]] %in% i.idx2 )]
573584
574585 # create ID-only empty data using original data as templates
575- h.empty <- horizons [0 , , drop = FALSE ][seq_along(i.idx2 ), , drop = FALSE ]
576- h.empty [[pid ]] <- newid
577- s.empty <- sites [0 , , drop = FALSE ][seq_along(i.idx2 ), , drop = FALSE ]
578- s.empty [[pid ]] <- newid
579-
580- # reorder to original id (+ top depth for horizons)
581- horizons <- rbind(horizons , h.empty )
582- horizons <- horizons [order(horizons [[pid ]], horizons [[depths [1 ]]]),]
583-
584- sites <- sites [which(! sites [[pid ]] %in% h.empty [[pid ]]), , drop = FALSE ]
585- sites <- rbind(sites , s.empty )
586- sites <- sites [order(sites [[pid ]]), , drop = FALSE ]
586+ if (length(newid ) > 0 ) {
587+ h.empty <- .create_placeholder_df(horizons , length(newid ), aqp_df_class(object ))
588+ h.empty [[pid ]] <- newid
589+ s.empty <- .create_placeholder_df(sites , length(newid ), aqp_df_class(object ))
590+ s.empty [[pid ]] <- newid
591+ # reorder to original id (+ top depth for horizons)
592+ horizons <- data.table :: rbindlist(list (horizons , h.empty ))
593+ horizons <- horizons [order(horizons [[pid ]], horizons [[depths [1 ]]]), ]
594+
595+ sites <- sites [which(! sites [[pid ]] %in% h.empty [[pid ]]), , drop = FALSE ]
596+ sites <- data.table :: rbindlist(list (sites , s.empty ))
597+ sites <- sites [order(sites [[pid ]]), , drop = FALSE ]
598+ }
587599
588600 if (inherits(object , ' SoilProfileCollection' ) && SPC ) {
589- object @ site <- sites
590- replaceHorizons(object ) <- horizons
601+ object @ site <- .as.data.frame.aqp( sites , aqp_df_class( object ))
602+ replaceHorizons(object ) <- .as.data.frame.aqp( horizons , aqp_df_class( object ))
591603 return (object )
592604 } else {
593605 return (list (
0 commit comments