How can I make my for loop return only the first match of an ifelse statement?
Here is my data frame:
df <- structure(
list(
x0 = c("0", "0", "0", "0", "0", "0", "0", "0",
"0", "0"),
x1 = c("0", "0", "0", "0", "0", "0", "0", "0", "0",
"0"),
x2 = c("0", "0", "0", "0", "0", "0", "0", "0", "0", "0"),
x3 = c("0", "0", "0", "0", "1", "0", "0", "0", "0", "0"),
x4 = c("0", "0", "0", "0", NA, "0", "0", "0", NA, "0"),
x5 = c("0",
"0", "0", "0", NA, "0", "0", "0", NA, "0"),
x6 = c("0", "0",
"0", "0", NA, "0", "0", "0", NA, "0"),
x7 = c("0", "0", "0",
"0", NA, "0", "0", "0", NA, "0"),
x8 = c("0", "0", "0", "0",
NA, "0", "0", "0", NA, "0"),
x9 = c("0", "0", "0", "0", NA,
"0", "0", "0", NA, "1"),
x10 = c("0", "0", "0", "0", NA,
"0", "0", "1", NA, "1"),
x11 = c("0", "0", "0", "0", NA,
"0", "0", "1", NA, "2"),
x12 = c("0", "0", "0", "0", NA,
"0", "0", "0", NA, "2"),
x13 = c("0", "0", "0", "0", NA,
"0", "0", "1", NA, "3"),
x14 = c(NA, NA, "0", "0", NA, NA,
NA, "2", NA, NA),
x15 = c(
NA_character_,
NA_character_,
NA_character_,
NA_character_,
NA_character_,
NA_character_,
NA_character_,
NA_character_,
NA_character_,
NA_character_
)
),
.Names = c(
"x0",
"x1",
"x2",
"x3",
"x4",
"x5",
"x6",
"x7",
"x8",
"x9",
"x10",
"x11",
"x12",
"x13",
"x14",
"x15"
),
row.names = c(NA, 10L),
class = "data.frame"
)
and here is what the expected output that I would like to achieve:
df$expectedoutput <- c(NA, NA, NA, NA, NA, NA, NA, 'x14', NA, 'x11')
and here is my attempt to obtain the said output:
df$newvar <- NA
for (i in 1:16) {
df$newvar <- ifelse(df[,i] == "2" & is.na(df$newvar),
colnames(df[i]), NA)
}
I believe that my problem is that the for loop that I've created goes on to the end and overwrites the first match that occurs, e.g. for row 10, instead of finishing on the column name for df[10,12] the loop continues to df[10,16] and therefore returns an NA However, I could be wrong and perhaps this isn't my problem.
Aucun commentaire:
Enregistrer un commentaire