1

I have read in a csv file about weather on days. One of the variables is called winddirection (windrichting) but it is given in degrees and 0 and 990 have special meaning.

I want to change the numbers to North/South/West/East but when I used the replace function it changed the datatype of the whole vector to char which prevented my next replace with a range to work. So now I ended up with an if/else if/else statement but I can't get it to work. Also I get an error condition has length > 1. Can anyone help me get this to work so I have the ranges 45-135 to east, 135-225 south, etc.

here is my code where mydata$DD is the variable for wind direction with over 2000 values.

windrichting <- mydata$DD 
windrichting <- if (windrichting == 990 ){
  windrichting == "Veranderlijk"
} else if (windrichting>45 && windrichting<=135){
  windrichting == "Oost"
} else if (windrichting>135 && windrichting<=225){
  windrichting == "Zuid"
} else if (windrichting>225 && windrichting <=315){
  windrichting == "West"
} else if (windrichting ==0){
  windrichting == "Windstil"
} else windrichting == "Noord"
ase
  • 13,231
  • 4
  • 34
  • 46
NickW
  • 25
  • 5
  • See `?cut` and -e.g.- [this](http://stackoverflow.com/questions/8233846/cut-function-in-r-exclusive-or-am-i-double-counting) – alexis_laz Feb 17 '17 at 14:02
  • have a look at `ifelse` function. `a<-1:10; ifelse(a<2,"a",ifelse(a>=2&a<5,"b","c"))`. When you do `if (windrichting>45)` you are comparing a vector with a number. That's the cause of the error – DJJ Feb 17 '17 at 14:04

2 Answers2

1

Perhaps something along the lines of this?

tmp <- round((windrichting + 45) / 90) %% 8
tmp[windrichting == 990] <- 8
tmp <- factor(tmp, levels = 0:9, labels = c("Noord", "Oost", "Zuid", "West", "Veranderlijk", "Windstil"))
tmp[windrichting == 0] <- "Windstil"
windrichting <- tmp
Martin Valgur
  • 5,793
  • 1
  • 33
  • 45
  • when i try your code i get the error : Error in factor(tmp, levels = 0:7, labels = c("Noord", "Oost", "Zuid", : invalid 'labels'; length 4 should be 1 or 8 when i change 0:7 to 0:3 i get the error: In `[<-.factor`(`*tmp*`, windrichting == 0, value = "Windstil") : invalid factor level, NA generated – NickW Feb 17 '17 at 14:34
0

You can do this using an *apply function.

windrichting_text <- unlist(lapply(windrichting, function (x) {
    if (x == 990) {
        return("Veranderlijk") 
    } else if {
        ....
    } else {
        return ("Noord")
    })

This applies the function defined to all elements in the list.

PinkFluffyUnicorn
  • 1,260
  • 11
  • 20