mercredi 17 août 2016

r - How to create vector with for loops and ifelse

I'm having a problem with nested for loops and ifelse statements. This is my dataframe abund:

   Species Total C1 C2 C3 C4
1     Blue   223 73 30 70 50
2    Black   221 17 50 56 98
3   Yellow   227 29 99 74 25
4    Green   236 41 97 68 30
5      Red   224 82 55 21 66
6   Orange   284 69 48 73 94
7    Black   154  9 63 20 62
8      Red   171 70 58 13 30
9     Blue   177 57 27  8 85
10  Orange   197 88 61 18 30
11  Orange   112 60  8 31 13

I would like to add together some of abund’s columns but only if they match the correct species I’ve specified in the vector colors.

colors <- c("Black", "Red", "Blue")

So, if the Species in abund matches the species in color then add columns C2 through C4 together in a new vector minus. If the species in abund does not match the species in color then add a 0 to the new vector minus.

I'm having trouble with my code and hope it's just a small matter of defining a range, but I'm not sure. This is my code so far:

# Use for loop to create vector of sums for select species or 0 for species not selected
for( i in abund$Species)
{ 
  for( j in colors)
  {
    minus <- ifelse(i == j, sum(abund[abund$Species == i, 
       "C2"]:abund[abund$Species == i, "C4"]), 0)
  }
}

Which returns this: There were 12 warnings (use warnings() to see them) and this "vector": minus [1] 0

This is my target:

minus
[1] 150 204 0 0 142 0 145 101 120 0 0

Thank you for your time and help with this.

Aucun commentaire:

Enregistrer un commentaire