R/read_write.R

Defines functions update_xlsx clipboard_send clipboard_get write_spss get_spss

Documented in clipboard_get clipboard_send get_spss update_xlsx write_spss

##########
### write/read to/from spss

get_spss <- function(file){
  #' Load spss data with labels converted to factors
  #'
  #' This function loads an spss .sav file, and creates a dataframe with the description,
  #' type and labels of all variables in the data file. This function automatically applies
  #' as_factor to the data, converting all variables with labels in spss to factors in R.
  #'
  #' To convert labels to factors function \code{haven::as_factor(.,only_labelled = TRUE,ordered=TRUE)} is used.
  #' For details, see \code{?as_factor}.
  #'
  #' The dataframe with the description of all variables contains the following information:
  #' \itemize{
  #'  \item \strong{var}: Variable name
  #'  \item \strong{name}: Variable label
  #'  \item \strong{class}: Variable class
  #'  \item \strong{valid}: Number of valid cases
  #'  \item \strong{n.na}: Number of \code{NA}'s
  #'  \item \strong{n.distinct}: Number of distinct values
  #' }
  #'
  #' @param file A characater string with the location of the spss file to be loaded.
  #' @return A list with two components:
  #' \itemize{
  #'  \item \strong{sav}\emph{(dataframe)}: with the actual data
  #'  \item \strong{vars}\emph{(dataframe)}: with the description of all variables
  #' }
  #'
  #' @examples
  #' spss.data <- get_spss(file)$sav
  #'
  #' spss <- get_spss(file)
  #' spss.data <- spss$sav
  #' spss.vars <- spss$vars

  spss <- read_spss(file)
  #spss <- as_factor(spss,only_labelled = TRUE,ordered=TRUE)
  spss <- as_factor(spss,only_labelled = TRUE)
  vars <- df_summary(spss)

  return(list(sav=spss,vars=vars))
}

write_spss <- function(df,file,max=255){
  #' Save spss data
  #'
  #' This function saves an spss '.sav' file removing known erros. String with length 0 are tranformed to " ". Also,
  #' all character string are truncated to max length of paramenter 'max' and [[:cntrl:]] string are removed.
  #'
  #' @param df The dataframe to be exported to sav format.
  #' @param file A characater string with the location of the spss file to be saved.
  #' @param max Maximum size of character strings.
  #' @return NULL
  #'
  #' @examples
  #' spss.data <- write_sav(df,file)

  df <- as.data.frame(purrr::map(df,function(x){
    z <- x
    if(is.character(x) == TRUE){
      z <- stringr::str_replace_all(stringr::str_trunc(z,max),'[[:cntrl:]]','')
      if (max(nchar(as.character(x)))==0){
        z <- rep(" ",length(x))
      }
    }
    attributes(z) <- attributes(x)
    return(z)
  }))

  ret <- haven::write_sav(df,file)
  return(ret)
}

##########
### write/read dataframes to/from clipboard

clipboard_get <- function(header = TRUE){
  #' Import dataframe from clipboard generated by EXCEL. Before running this function in R, select
  #'the appropriate cell range in EXCEL and press <CTRL+C>.
  #'
  #' @param NULL
  #' @return df The dataframe imported from Excel.
  #'
  #' @examples
  #' clipboard_get()
  #'
  #'
  df <- read.table('clipboard',sep="\t",dec = ".",header = header)
  return(df)
}

clipboard_send <- function(df){
  #' Export dataframe to clipboard. After running this function in R, select a target cell in EXCEL
  #' and press <CTRL+V>.
  #'
  #' @param df The dataframe to be exported to Excel.
  #' @return NULL
  #'
  #' @examples
  #' clipboard_send(df)
  #'
  write.table(df,'clipboard',sep="\t",row.names = FALSE,dec = ".")
}

##########
### write/read to/from excel

update_xlsx <- function(df,file,sheet){
  #' Update xlsx workbook with a dataframe. A new spreadsheet can be created or updated.
  #'
  #' @param df The dataframe to be added to the workbook.
  #' @param file A characater string with the location of the xlsx file.
  #' @param sheet A characater string with the name of the sheet to be created/updated.
  #' @return Boolen value indicating if updating of the file was successful
  #'
  #' @examples
  #' update_xlsx(df,wb,sheet)

  wb <- loadWorkbook(file)
  sheets <- sheets(wb)

  if (sheet %in% sheets){
    removeWorksheet(wb,sheet)
    addWorksheet(wb,sheet)
    new.sheets <- sheets(wb)
    pos <- match(sheets,new.sheets)
    worksheetOrder(wb) <- pos
  } else {
    addWorksheet(wb,sheet)
  }

  writeData(wb, sheet,df)
  saveWorkbook(wb, file, overwrite = TRUE)

}

##########
### paste copied (CTRL+C) items
### use datapasta
### dpasta() instead of dput()
neale-eldash/pd documentation built on June 26, 2021, 10:47 a.m.