How to get a counting table for unique values โ€‹โ€‹in a column

I have this mymat matrix. I know I can do table((mymat[,"col1"]) to get the number of each element in col1 . However, I only need to count if there are unique values โ€‹โ€‹in col2. For mymat below I want to get this result :

 app gg chh 1 2 1 

mymat

 col1 col2 app d app d gg e gg f gg e chh f chh f chh f 
+5
source share
4 answers

You can use unique for a subset of the data (works for matrix and data.frame ), and then table is called:

table(unique(mymat)[,1])

It returns

 # app chh gg # 1 1 2 
+8
source

You can use duplicated to subset the data and then call table :

 table(subset(df, !duplicated(paste(col1, col2)), select = col1)) #app chh gg # 1 1 2 

As a second option, here is the dplyr approach:

 library(dplyr) distinct(df) %>% count(col1) # or distinct(df, col1, col2) if you have other columns #Source: local data frame [3 x 2] # # col1 n # (fctr) (int) #1 app 1 #2 chh 1 #3 gg 2 
+7
source

This is a count of nonzero values โ€‹โ€‹in the table () - the result

 rowSums(table(df$col1, df$col2)!=0) 

result:

 app chh gg 1 1 2 

data used:

 df <- read.table(header=TRUE, text= "col1 col2 app d app d gg e gg f gg e chh f chh f chh f") 
+1
source

Other suggestions are better, but here I am throwing another opportunity just for a change:

 apply(dcast(df, col1 ~ col2)[-1], 1, function(x) {sum(x > 0)}) 
0
source

Source: https://habr.com/ru/post/1245096/


All Articles