I have a question. I have a column indicating the district as a string “district1”, for example. However, now I would like to ass another column with just number of the district. I am using if else statements but this is exhausting.
Below I give just a example of the more than 30 districts I have:
### generate dataframe
d <- data.frame(variable=c("district1", "district1", "district1", "district1", "district2", "district2", "district3"))
d$id1 = ifelse(d$variable=="district1", 1,
ifelse(d$variable=="district2", 2,
ifelse(d$variable=="district3", 3, NA)))
Thus I was wondering if it was possible to do it with a loop. However the looping structure is not well done:
# for (i in 1:30){
# d$id1 = ifelse(d$variable=="districti", i, NA)
# }
Could someone help me to do in a more elegant way? This would be great Best
Aucun commentaire:
Enregistrer un commentaire