J.M. J.M. - 2 months ago 8
R Question

R - for loop alternative to conditionally populating tuples?

Have a

data.frame
with numeric values, and a character vector. The character vector is not a named character (unlike here).

The toy code below achieves what I'm looking to do, but I've been trying to shy away from
for
loops and either use the
*apply
family or other functions available in
{base}
.

df = data.frame(act_val = c(1:10))
temp = letters[1:10]

for (i in 1:length(temp)){
df$act_name[df$act_val == i] = temp[i]
}


So, IFF
act_val == 1
then
act_name == "a"
. I realize this is somewhat a bastardized version of a named character vector, where the position of the character is effectively being used as what the value
names()
would be.

All that said, there must be a more R-like way?

Michael

Answer

You can vectorize the lookup with temp[df$act_val] and then assign to the column:

df$act_name = temp[df$act_val]