vendredi 14 septembre 2018

r if ... do multiple things in else-argument

I use read.csv to read two different sets of data: rawdata1 and rawdata2. rawdata 1 always exists while rawdata2 may not be available.

rawdata1 <- read.csv(file=rawdata1.csv)
rawdata2 <- read.csv(file=rawdata2.csv)

Each .csv has two columns with data (date is matching):

date     value

What I want to do: In case there is a rawdata2.csv available, I want to create a new table "rawdata" by joining rawdata1 and rawdata2 by "date" (I manage to do that). If not, I want to create "rawdata" by assigning rawdata1 to it and adding a new column with value 0 (to represent the missing data for rawdata2, which is 0 if missing). I think I need this column because calculations depend on both values.

How I tried to do it:

if(exists("rawdata2")) {
  rawdata <- left_join(rawdata1,rawdata2,by = "date")
} else {
  rawdata <- rawdata1 %>%
    rawdata$value_2 <- 0
}

Error:

Error in rawdata_bezug %>% rawdata$Zaehlerstand_abgabe <- 0 : 
  could not find function "%>%<-"

Doing it with dplyr/tidyr doesn't seem to work, but I couldn't find another solution so far.

Thanks for the help :)

Aucun commentaire:

Enregistrer un commentaire