Juanchi
Juanchi

Reputation: 1166

Mathematical operations inside a xtabs() table in R

How can I sum two factor levels inside a table? For example, I'd like to sum versicolor + virginica in this case...

t1 <- xtabs(~Species, iris)

> t1
# Species
#    setosa versicolor  virginica 
#        50         50         50 

and then remove versicolor and virginica, leaving the new level "sumV" and its value.

Upvotes: 3

Views: 278

Answers (2)

akrun
akrun

Reputation: 887098

We can transform the dataset by changing the 'versicolor', and 'virginica' to a new value 'sumV' and then do the xtabs.

xtabs(~Species,transform(iris, Species= c('setosa', 
           'sumV')[(Species %in% c('versicolor', 'virginica'))+1L]))
#Species
#setosa   sumV 
#    50    100 

Or as @Ananda Mahto suggested, we can use replace with grep

xtabs(~ Species, transform(iris, Species = 
  replace(as.character(Species), grepl("^v", Species), "sumV")))

Upvotes: 3

Nancy
Nancy

Reputation: 4089

t1 <- xtabs(~Species, iris)

#Species
#    setosa versicolor  virginica 
#        50         50         50 

Then sum the values you want and assign them to a new level:

t1["sumV"]  = t1["versicolor"] + t1["virginica"]

#    setosa versicolor  virginica       sumV
#        50         50         50        100 

Finally remove the values that you don't want to keep:

t1[-c(2,3)]

#setosa   sumV 
#    50    100 

Upvotes: 3

Related Questions