While running the following code I get the error: unexpected '}' in "}"
However, there are no open double or single brackets
df3["Zone"]<-1
usq<-0
for(i in 1:nrow(df3)){
if(df3$state = "Kerala"){
paste(df3$Zone[i] <- "SW")
}
else if(df3$state = "Karnataka"){
paste(df3$Zone[i] <- "SW")
}
else if(df3$state = "Goa"){
paste(df3$Zone[i] <- "SW")
}
else if(df3$state = "Maharashtra"){
paste(df3$Zone[i] <- "NW")
}
else if(df3$state = "Gujarat"){
paste(df3$Zone[i] <- "NW")
}
else if(df3$state = "Tamilnadu"){
paste(df3$Zone[i] <- "SE")
}
else if(df3$state = "Andhra Pradesh"){
paste(df3$Zone[i] <- "SE")
}
else if(df3$state = "Pondicherry"){
paste(df3$Zone[i] <- "SE")
}
else if(df3$state = "Orissa"){
paste(df3$Zone[i] <- "NE")
}
else if(df3$state = "West Bengal"){
paste(df3$Zone[i] <- "NE")
}
usq<- print(df3)
df3.1<-data.frame(usq)
}
I would also like to know how to write a single if statement for each zones ie for states Kerala, Karnataka and Goa it should paste 'SW' and so on other zones
Thanks in advance!
CodePudding user response:
Not sure about your first issue but to combine if statements, you can use the or operator "||"
else if((df3$state == "Karnataka") || (df3$state == "Kerala") || ...)
Not too familiar with R but that should work
CodePudding user response:
If you just want to add new columns based on data which can be structured in other tables, joining is the way to go:
library(tidyverse)
zones <- tibble(state = c("Karnataka", "Kerala"), zone = c("SW", "SW"))
zones
#> # A tibble: 2 x 2
#> state zone
#> <chr> <chr>
#> 1 Karnataka SW
#> 2 Kerala SW
df3 <- tibble(state = c("Kerala", "Karnataka"))
df3
#> # A tibble: 2 x 1
#> state
#> <chr>
#> 1 Kerala
#> 2 Karnataka
df3 %>% left_join(zones)
#> Joining, by = "state"
#> # A tibble: 2 x 2
#> state zone
#> <chr> <chr>
#> 1 Kerala SW
#> 2 Karnataka SW
Created on 2021-10-06 by the reprex package (v2.0.1)