简体   繁体   中英

count of numeric values by column with data.table (R)

DC<-data.table(l=c(0,0,1,4,5),d=c(1,2,0,0,1),y=c(0,1,0,1,7))

Hello, how can I get a count of a particular value in a column using data.table? I tried the following:

DC[, lapply(.SD, function(x) length(which(DC==0)))] 

But this returns the count of zeros in the entire dataset, not indexing by column. So, how do I index by column? Thanks

The question is not very well formulated, but I think @Sathish answered it perfectly in the comments.

Let's write it here one more time: to me colSums(DC == 0) is one answer to the question.
All credit goes to @Sathish. Very helpful.

If I understand your question, you'd like to form a frequency count of the values that comprise a given data table column. If that is true, let's say that you want to do so on column d of the data table you supplied:

> DC <- data.table(l=c(0,0,1,4,5), d=c(1,2,0,0,1), y=c(0,1,0,1,7))
> DC[, .N, by = d]
   d N
1: 1 2
2: 2 1
3: 0 2

Then, if you want the count of a particular value in d , you would do so by accessing the corresponding row of the above aggregation as follows:

> DC[, .N, by = d][d == 0, N]
[1] 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM