R/get_timetable_for_variable.R

Defines functions get_timetable_for_variable

Documented in get_timetable_for_variable

#' @title Returns data for one variable of a data set.
#' @description Extracts a data set for one variable where each row is on region (e.g. NUTS3-region) and each column contains the values for one year.
#'
#' @param VarName character string, with the name of the variable for which we want the time table. Can be left out, if data set contains only values for one variable.
#' @param data data frame, from which you want to extract your data. The data frame must contain a column called variable. Default is the EntrancesData data set.
#' @param NUTS_IDs numeric vector, containing the IDs of the regions, e.g. NUTS3 IDs. If not defined, all regions contained in the data set are included.
#' @param years numeric vector, containing all years of interest. Default is 1990 to 2020.
#' @return dataframe, format: first column NUTS_ID, other columns values for each year
#' @export
get_timetable_for_variable<- function(VarName, data=EntrancesData, NUTS_IDs="all", years=c(1990:2020)){
  new_msg<-0 #variable to check if function has generated a new (warning) message
  years_char<-as.character(years)
  dataout<-data.frame(matrix(0, ncol = (1+length(years)), nrow = 0)) #empty data frame
  colnames(dataout)<-c("NUTS_ID", years_char)
  dataout$NUTS_ID<-as.character(dataout$NUTS_ID)
  suppressWarnings(if (NUTS_IDs=="all") {NUTS_IDs=unique(data$NUTS_ID)})
  for (row in NUTS_IDs){
    values<-c(row)
    for (col in years) {
      val<-data$value[which(data$NUTS_ID==row & data$year==col & data$variable==VarName)]
      if (length(val)>1) {
        if (length(unique(val))>1) {
          new_msg<-1
          if (exists("messages")) assign("messages", c(messages, paste("several values for observation", VarName, col, row, ". First value was used", sep=" ")), envir = .GlobalEnv)
          if (!exists("messages")) assign("messages", paste("several values for observation", VarName, col, row, ". First value was used", sep=" "), envir = .GlobalEnv)
          }
        val<-val[1]
        }
      if (length(val)==0) {val<-NA}
      values<-c(values, val)
    }
    dataout[nrow(dataout)+1, ]<-values
  }
  for (col in 2:ncol(dataout)){
    dataout[,col]<-as.numeric(dataout[,col])
  }
  if (exists("messages") & new_msg==1) print("check display_messages() to see warning messages. Messages will be deleted after displaying.")
  return(dataout)
  }
THartl1/EntrancesDataPackage documentation built on Dec. 18, 2021, 4:01 p.m.