I have a simple data frame like this:
col1 col2
a 1
b 2
a 2
I'll refer to this data frame as table
. I am trying to create variables a1
and a2
where the value of a1
would be 1 in this instance and the value of a2
would be 2. My current attempt is this to get a1
and a2
:
for (i in 1:nrow(table)) {
# Getting a1
if (col1 == 'a') {
a1 <- as.numeric(table %>% dplyr::select(col2))
} else {
if (a1 != 0) {
a1 <- a1
} else {
a1 <- 0
}
}
# Getting a2
if (col1 == 'a' & a1 != 0) {
a2 <- as.numeric(table %>% dplyr::select(col2))
} else {
if (a2 != 0) {
a2 <- a2
} else {
a2 <- 0
}
}
}
With this I get a1
and a2
to be 2. So the loops are correctly identifying the 2nd instance where col1 = 'a'
but for a1
I need the first instance where col1 = 'a'
which keeps getting overwritten.
Any suggestions?