R/asthistibble.R

Defines functions asthistibble

Documented in asthistibble

#' Copy tibble attributes
#'
#' Converts a data frame into a tibble copying all attributes.
#' 
#' @param tibble a tibble object.
#' @param x a data frame with the same columns of \code{tibble}.
#'
#' @returns A tibble.
#' 
#' 
#' @keywords tibblemanagement
#' 
#' @examples
#' # tibble generated by haven
#' input <- system.file("extdata/reds", package = "ILSAmerge")
#' tib <- do.call(rbind,justload(inputdir = input,population = "BCGV1"))
#' 
#' # Remove all tibble attributes
#' x <- tib
#' class(x) <- "data.frame"
#' for(i in 1:ncol(x)){
#'   attributes(x[,1]) <- NULL
#' }
#' 
#' # Mix variables 
#' set.seed(1919)
#' x <- x[,sample(ncol(x))]
#' head(x)[,1:10]
#' tib
#' 
#' asthistibble(tibble = tib, x = x)
#'
#' @export
#

asthistibble <- function(tibble,x){
  
  if(!inherits(tibble, "tbl_df"))
    stop(c("\nInvalid input for 'tibble'.",
           "\nIt should be a tibble."),call. = FALSE)
  
  if(!(inherits(x,"data.frame")&length(class(x))==1))
    stop(c("\nInvalid input for 'x'.",
           "\nIt should be a plain data frame."),call. = FALSE)
  
  
  if(ncol(x)!=ncol(tibble))
    stop("Invalid input, 'tibble' and 'x' should have the same number of columns.",call. = FALSE)
  
  if(length(setdiff(colnames(tibble),colnames(x)))>0)
    stop("Invalid input, 'tibble' and 'x' should have the same column names.",call. = FALSE)
  
  
  
  out <- x[,colnames(tibble)]
  class(out) <- class(tibble)
  attributes(out) <- attributes(tibble)
 
  
  for(i in 1:ncol(out)){
    atr <- attributes(tibble[,i,drop = TRUE])
    if(!is.null(atr)){
      attributes(out[,i, drop = TRUE]) <- atr
    }
    
  }
  
 
  
  out
}

Try the ILSAmerge package in your browser

Any scripts or data that you put into this service are public.

ILSAmerge documentation built on April 11, 2025, 5:54 p.m.