How do I fix this for loop that takes a value in one column to change one in another?

Viewed 31

It's been a while since I've touched for loops. I am simply trying to check if the value in the LocationID column is 1, and if so, set the value in the corresponding row in RegionID to 4. It should run through every value in the LocationID column.

for (i in 1:length(df$LocationID)) {
  if (df_7$LocationID == 1) {
    df_7$RegionID = 4
  }
}

From my understanding, the code I've come up with here just checks the first value ~44000 times (the length of the dataset) and then sets every value of RegionID to 4.

Any help is greatly appreciated!

1 Answers

We need to specify the index i to subset the value. In the OP's code, the if condition is checking the whole column 'LocationID' and if is not vectorized, so it expects a single TRUE/FALSE i.e a vector of length 1

for (i in seq_along(df_7$LocationID)) {
  if(df_7$LocationID[i] == 1) {
    df_7$RegionID[i] <- 4
   }
  }

In R, we can vectorize this easily

df_7$RegionID[df_7$LocationID == 1] <- 4

_ Or with ifelse

df_7$RegionID <- with(df_7, ifelse(LocationID == 1, 4, RegionID))

Or another option with tidyverse

library(dplyr)
df_7 <- df_7 %>%
            mutate(RegionID = case_when(LocationID == 1 ~ 4, TRUE ~ RegionID))
  

Or with data.table

library(data.table)
setDT(df_7)[LocationID == 1, Region_ID := 4]
Related