Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用.N时显示零行_R_Data.table - Fatal编程技术网

R 使用.N时显示零行

R 使用.N时显示零行,r,data.table,R,Data.table,我有一个大致如下的数据表: DT <- data.table(disease = c(0,0,1,1,1,1), hospital = c(2,2,4,3,3,2)) hospital N 1: 1 0 2: 2 2 2: 3 1 3: 4 1 5: 5 0 但是如果f.ex。我希望医院的数量为5家,我得到的data.table(它不必是data.table,也可以是矩阵)看起来像这样: DT <-

我有一个大致如下的数据表:

DT <- data.table(disease = c(0,0,1,1,1,1),
   hospital = c(2,2,4,3,3,2))
   hospital N
1:        1 0
2:        2 2
2:        3 1
3:        4 1
5:        5 0
但是如果f.ex。我希望医院的数量为5家,我得到的data.table(它不必是data.table,也可以是矩阵)看起来像这样:

DT <- data.table(disease = c(0,0,1,1,1,1),
   hospital = c(2,2,4,3,3,2))
   hospital N
1:        1 0
2:        2 2
2:        3 1
3:        4 1
5:        5 0
最好分类。它也可以是N的向量,只要它统计零事故的医院(但它肯定要被分类)

我有一个相当大的数据集(还有其他列),这是一个循环,所以它必须相当快


提前谢谢。

我想这是一个错误,因为样本数据和预期输出似乎不匹配(请参阅我上面的评论)

除此之外,您可以使用
table

table(DT[, hospital := factor(hospital, 1:5)])[2, ]
#1 2 3 4 5
#0 1 2 1 0
或者您想要疾病=0和疾病=1计数的总和

colSums(table(DT[, hospital := factor(hospital, 1:5)]))
#1 2 3 4 5
#0 3 2 1 0

在这两种情况下,返回对象都是命名的
int
vector。

我很困惑。为什么
N=2
代表
hospital=2
?该医院有两个
disease=0
条目和一个
disease=1
条目。这怎么会给出2的计数?@sindri_baldur仍然不符合OPs的预期输出(见我上面的评论)。另外,根据OP,作为返回对象的向量是正确的。在我最后的评论中有一个错误。这应该是可行的(为了得到一个data.table,但我现在看到OP对于一个向量是可以的),
DT[disease==1,(table(factor(hospital,1:5))][,(hospital=V1,N)]
。非常确定OP的预期输出只有一个输入错误。@sindri_baldur确定,或者干脆
data.table(hospital=1:5,N=table(DT[,hospital:=factor(hospital,1:5)])[2,]
。哦,是的,有一个输入错误。我编辑了几次表格。忘了注意我最后用的是哪一个。这两个答案都是它应该做的。非常感谢,这帮了大忙。
DT[.(hospital = 1:5, disease = 1), on = .(hospital, disease), .N, by = .EACHI
   ][, .(hospital, N)]

   hospital N
1:        1 0
2:        2 1
3:        3 2
4:        4 1
5:        5 0