Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

else {} statement ignored in a for loop [closed]

I have a tibble, Agencies, with two columns as follows:

> head(Agencies, 10)
# A tibble: 10 x 2
   AgencyNumber    State
          <int>    <chr>
 1            1       AR
 2            2 Arkansas
 3            3    Texas
 4            4    Texas
 5            5       TX
 6            6       IL
 7            7 Illinois
 8            8 Illinois
 9            9       IL
10           10       IL

I'm trying to add a column (Agencies$STATE) with the full state name. If Agencies$State is an abbreviation, it should use the abbr2state function to save the full name to the new column. If Agencies$State already has the full name, it should store the value of Agencies$State to the new column.

I'm using the following code:

Agencies$STATE <- "NA"

for(i in 1:nrow(Agencies)) {
  if(nchar(Agencies$State[i] == 2)) {
    Agencies$STATE[i] <- abbr2state(Agencies$State[i]) 
  }
  else {
    Agencies$STATE[i] <- Agencies$State[i]
  }
}

The output is unexpected. It appears to evaluate the first if statement as expected, but ignores the else statement.

> head(Agencies, 10)
# A tibble: 10 x 3
   AgencyNumber    State    STATE
          <int>    <chr>    <chr>
 1            1       AR Arkansas
 2            2 Arkansas     <NA>
 3            3    Texas     <NA>
 4            4    Texas     <NA>
 5            5       TX    Texas
 6            6       IL Illinois
 7            7 Illinois     <NA>
 8            8 Illinois     <NA>
 9            9       IL Illinois
10           10       IL Illinois

I'm a bit new to R so this may be an obvious error, but I'm missing it.

Any suggestions on why this isn't doing what I expect?

Thanks, Jeff

like image 877
Jeff Jarvis Avatar asked Nov 28 '25 04:11

Jeff Jarvis


1 Answers

Your statement nchar(Agencies$State[i] == 2) should be (nchar(Agencies$State[i]) == 2) You misplace the parenthesis

You can also use dplyr to avoid the loops

library(dplyr)
Agencies %>% 
  mutate(state =  ifelse( stringi::stri_length(State) == 2,abbr2state(State),State))
like image 116
Harlan Nelson Avatar answered Nov 30 '25 18:11

Harlan Nelson