Most pro R users have advised me never to use loops in R. Use application functions instead. The problem is that it is not intuitive to write an application equivalent for each / while loop if you are not familiar with functional programming. Take for example the example below.
F <- data.frame(name = c("a", "b", "c", "d"), var1 = c(1,0,0,1), var2 = c(0,0,1,1), var3 = c(1,1,1,1), clus = c("one", "two", "three", "four")) F$ObjTrim <- "" for (i in 1:nrow(F)) { for (j in 2:(ncol(F)-1)) { if(F[i, j] == 1) {F$ObjTrim[i] <- paste(F$ObjTrim[i], colnames(F)[j], sep = " ") } } print(i) }
The goal here is to create the "ObjTrim" variable, which takes the value of all column names that have value == 1. Can anyone suggest a good equivalent to this equivalent?
The above code, for example, will give:
name var1 var2 var3 clus ObjTrim 1 a 1 0 1 one var1 var3 2 b 0 0 1 two var3 3 c 0 1 1 three var2 var3 4 d 1 1 1 four var1 var2 var3
Thanks!
source share