R An if else statement inside a for loop -
i have data table made of 3 columns assigned variable g.
g # v1 v2 v3 # [1,] 1 yes 3 # [2,] 4 no 6 # [3,] 7 no 9 # ...
i'm trying create list, m, checking see if values in g[,2] "yes" or "no", , pasting string 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 try return m, returns null. want m this:
m # abc1defyesghi3 # ghi2defnoabc9
can point out doing wrong here? thank much!
a for
loop doesn't return in r. typically want update variable continue using after for
loop. example:
m <- "intialize" # initialize, better `list()` for(i in 1:nrow(g)){ if(g[i,2]=='no'){ # paste position 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 position of vector m m[i] <- paste0("abc", g[i,1], "def", g[i,2], "ghi", g[i,3],"\n") } else { null } } m > ...
Comments
Post a Comment