KT_1
KT_1

Reputation: 8484

Pick out column with positive values in

I am working on a dataframe and I am trying to use R to calculate the column name which has data in. I have an example dataframe listed below:

df <-structure(
  list(
    area = structure(1:9, 
      .Label = c("a", "b", "c", "d", "e", "f", "g", "h", "i"), 
       class = "factor"
    ), 
    cat = c(5L, 0L, 0L, 0L, 0L, 0L, 0L, 3L, 0L), 
    dog = c(0L, 10L, 0L, 0L, 0L, 0L, 0L, 0L, 11L), 
    rabbit = c(0L, 0L, 0L, 3L, 0L, 0L, 0L, 0L, 0L), 
    horse = c(0L, 0L, 8L, 0L, 0L, 0L, 0L, 0L, 0L), 
    sheep = c(0L, 0L, 0L, 0L, 9L, 0L, 0L, 0L, 0L), 
    mouse = c(0L, 0L, 0L, 0L, 0L, 5L, 0L, 0L, 0L), 
    rat = c(0L, 0L, 0L, 0L, 0L, 0L, 2L, 0L, 0L)
  ), 
  .Names = c("area", "cat", "dog", "rabbit", "horse", "sheep", "mouse", "rat"), 
  class = "data.frame", 
  row.names = c(NA, -9L)
)

In the columns from 'cat' to 'rat' there are positive values in ONLY ONE of the columns (the rest are zeros). How would I get R to add an extra column called 'animal' to give me each area with the animal name in (from the column name) for which there are positive values i.e. the column 'animal' would read cat, dog, horse, rabbit, sheep etc.?

Any help or guidance where to look for this would be gratefully received.

Many thanks in advance.

Upvotes: 1

Views: 123

Answers (1)

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

df$animal <- names(df)[-1][apply( df[,-1] , 1, which.max )]
df
#  area cat dog rabbit horse sheep mouse rat animal
#1    a   5   0      0     0     0     0   0    cat
#2    b   0  10      0     0     0     0   0    dog
#3    c   0   0      0     8     0     0   0  horse
#4    d   0   0      3     0     0     0   0 rabbit
#5    e   0   0      0     0     9     0   0  sheep
#6    f   0   0      0     0     0     5   0    pos
#7    g   0   0      0     0     0     0   2    pos
#8    h   3   0      0     0     0     0   0    cat
#9    i   0  11      0     0     0     0   0    dog

Upvotes: 1

Related Questions