Loulou Loulou -4 years ago 82
R Question

fast way to apply an if loop within a for loop

This is my df :

a <- data.frame(x1 = 1:3, x2 = 0, GF = c("Pelagic", "Demersal", "Cephalopod"), Pelagic = 6, Demersal = 7, Cephalopod = 8)


I have a list like this :

GF_list <- c("Pelagic", "Demersal", "Cephalopod")


I want to attribute to the x2 column the value corresponding to the GF of the line. So I do this

for (i in 1 : nrow(a)) {
for (j in 1 : length(GF_list)) {
if (a$GF[i] == GF_list[j]) {
a$x2[i] <- a[i,(ncol(a) + (- length(GF_list) + j))]
}}
}


But it takes a very long time ... (I have a large data frame)

Does it exist a faster way to applicate this attribution ? I think about a way which eliminates the first loop : "for (i in 1 : nrow(a))"

Thank you

Answer Source

One way is using apply row-wise and select the value of column from the GF column of that row.

a$x2 <- apply(a, 1, function(x) x[x[["GF"]]])
a
#  x1 x2         GF Pelagic Demersal Cephalopod
#1  1  6    Pelagic       6        7          8
#2  2  7   Demersal       6        7          8
#3  3  8 Cephalopod       6        7          8
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download