0

I do have an existing column with only numbers that correspond to codes about the weather (numbers corresponds to a type of precipitations and can be grouped, e.g. 80 to 82= rain, 86 to 90 = snow etc). Now I would like to return the type of precipitation (rain, snow) according to those codes in a new column.

I know this is a very rookie question, but I'm a total beginner in R so please save me :)

thanks in advance

I already created some values grouping numbers referring to the same type of precipitation:

x<-50:67
y<-80:82
a<-68:69
b<-83:84
c<-70:79
d<-85:86
e<-36:39

Then I tried to link these values to a text...not sure I did it the right way though:

type_list <- list(x = "rain", y = "rain", a = "mixed",b = "mixed",c = "snow", d ="snow")
Sotos
  • 51,121
  • 6
  • 32
  • 66
Sanda
  • 1
  • 1

1 Answers1

1

Why not just.

x <- 50:67
y <- 80:82
a <- 68:69
b <- 83:84
c <- 70:79
d <- 85:86
e <- 36:39

v[v %in% c(x, y)] <- "rain"
v[v %in% c(a, b)] <- "mixed"
v[v %in% c(c, d)] <- "snow"
v[v %in% e] <- "unknown"
v

 [1] "rain"    "unknown" "snow"    "rain"    "rain"    "rain"    "mixed"  
 [8] "rain"    "rain"    "snow"    "rain"    "rain"    "snow"    "unknown"
[15] "snow"    "snow"    "snow"    "rain"    "rain"    "snow"    "rain"   
[22] "rain"    "snow"    "snow"    "snow"    "unknown" "snow"    "mixed"  
[29] "snow"    "rain"    "rain"    "rain"    "rain"    "unknown" "rain"   
[36] "rain"    "snow"    "rain"    "unknown" "snow"    "rain"    "mixed"  
[43] "mixed"   "snow"    "rain"    "rain"    "unknown" "unknown" "rain"   
[50] "unknown"

Or within a data frame.

d <- within(d, {
  v[v %in% c(x, y)] <- "rain"
  v[v %in% c(a, b)] <- "mixed"
  v[v %in% c(c, d)] <- "snow"
  v[v %in% e] <- "unknown"
})
head(d)
#         v           x
# 1    rain -1.07816937
# 2 unknown -0.05166311
# 3    snow  0.58092897
# 4    rain -0.31734752
# 5    rain -2.95357980
# 6    rain -1.00310455

Data

set.seed(42)
v <- sample(sort(c(x, y, a, b, c, d, e)), 50, replace=TRUE)
d <- data.frame(v, x=rnorm(50))
jay.sf
  • 60,139
  • 8
  • 53
  • 110