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!
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
> ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With