Paul Paul - 16 days ago 7
R Question

counting frequency of values in R

I have a dataframe as follows

DATA <- read.table(text = "col1 col2
ATG AT
NA AT1
ATC AT2
ATD AT3
ATE AT3
ATF AT4
ATH AT4
ATI AT4
ATL AT4", header=TRUE)


I used

result<-data.frame(table(data$col2))


to get what I wanted

##result
col1 col2
1 AT
1 AT1
1 AT2
2 AT3
4 AT4


The problem is the second row in col1 has NA and should be counted as zero but I am unable to do that. It should be

##result
col1 col2
1 AT
0 AT1
1 AT2
2 AT3
4 AT4

Answer
dfs = read.table(text =
"col1 col2
ATG AT
NA AT1
ATC AT2
ATD AT3
ATE AT3
ATF AT4
ATH AT4
ATI AT4
ATL AT4", sep = " ", header = TRUE)

data.frame(xtabs( !is.na(col1) ~ col2, data = dfs))