Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R An if else statement inside a for loop

Tags:

r

I have a data table made of 3 columns that is assigned to a variable g.

g
#      V1   V2 V3
# [1,]  1  Yes  3
# [2,]  4   No  6
# [3,]  7   No  9
# ...

I'm trying to create a list, m, by checking to see if the values in g[,2] are "Yes" or "No", and then pasting some string into m.

m <- for(i in 1:nrow(g)){
  if(g[i,2]=='No'){
    paste0("ABC", g[i,1], "DEF", g[i,2], "GHI", g[i,3],"\n")
  } else if(g[i,2]=='Yes'){
    paste0("GHI", g[i,1], "DEF", g[i,2], "ABC", g[i,3],"\n")
  } else {NULL}
}

m
# NULL

However when I try to return m, it just returns NULL. I want m to look like this:

m
# ABC1DEFYesGHI3
# GHI2DEFNoABC9

Can someone point out what I am doing wrong here? Thank you very much!

like image 478
alki Avatar asked Dec 15 '22 13:12

alki


1 Answers

A for loop doesn't return anything in R. Typically you would want to update another variable that you would continue using after the for loop. For example:

m <- "intialize" # initialize, sometimes better as just `list()`
for(i in 1:nrow(g)){
  if(g[i,2]=='No'){
    # paste into position i of vector m
    m[i] <- paste0("ABC", g[i,1], "DEF", g[i,2], "GHI", g[i,3],"\n") 
  } else if(g[i,2]=='Yes'){
    # paste into position i of vector m
    m[i] <- paste0("ABC", g[i,1], "DEF", g[i,2], "GHI", g[i,3],"\n")
  } else {
  NULL
  }
}
m
> ... 
like image 131
Brandon Bertelsen Avatar answered Jan 07 '23 19:01

Brandon Bertelsen