trhood
trhood

Reputation: 13

table() in R needs to return zero if value is not present

I am relatively new to R, and I'm doing some dna sequence analysis. I wanted to know how to get the table function to return a zero if there are no N's in the sequence. Instead of returning zero it returns subscript out of bounds. I could do an if statement but I thought there might be a really simple way to fix this? Thanks for the help!

library(seqinr)
firstSet<-read.fasta("NC_000912.fna")
seqFirstSet<-firstSet[[1]]
length(seqFirstSet)
count(seqFirstSet,1)
count(seqFirstSet,2)
seqTable<-table(seqFirstSet)
seqTable[["g"]]
seqTable[["n"]]

Upvotes: 0

Views: 1335

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 146040

If your data is a factor with appropriate levels, then you'll have no problem:

> x <- factor(letters[1:3])
> y <- factor(letters[1:3], levels = letters)

> table(x)
x
a b c 
1 1 1 

> table(y)
y
a b c d e f g h i j k l m n o p q r s t u v w x y z 
1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 

> table(x)[["g"]]
Error in table(x)[["g"]] : subscript out of bounds

> table(y)[["g"]]
[1] 0

Just set the levels!

Upvotes: 3

Related Questions