J.M. J.M. - 1 year ago 61
R Question

R - for loop alternative to conditionally populating tuples?

Have a

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
loops and either use the
family or other functions available in

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]

act_val == 1
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
would be.

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


Answer Source

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

df$act_name = temp[df$act_val]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download