Search code examples
rif-statementfor-looplevels

Misunderstanding an if statement in a for loop


I am relatively new to R and I can not figure out a way of making my code work. I have a dataset with all the municipalities of the Netherlands and I want to print only the municipalities that are in my list named b. If I select a number inside my dataframe by using df[i] it also contains levels. Would it work without the levels?

df contains all municipality names of the Netherlands and b is a list of reshaped municipalities

df <- mun_neth$GM_NAAM
b <- list(gem_her$Nieuwe.gemeente)
for(i in df){
  a <- df[i]
  if(a in b){
     print(a)
}}

Solution

  • The correct syntax would be (read each line carefully and compare with yours.)

    df <- mun_neth$GM_NAAM
    b <- gem_her$Nieuwe.gemeente
    for(a in df){
      if(a %in% b){
         print(a)
    }}
    

    But look at intersect so you can do the work of the whole loop in a single call:

    intersect(df, b)