R "by"函数在与自创"nrow"函数配对时返回 NULL 值



我花了超过3个小时试图解决这个问题。我试图获得每个id的实例计数。我在"by"函数中创建了自己的函数,并测试了该函数,它为我获得了所有id的正确计数。。。但当我运行以下代码时,它会返回"NULL":

为了使其成为一个更实用的概念。。如果我想知道每个患者在我的机构进行了多少次"健康"+"实验室"访问,该怎么办?:

dataset #<- this is the name of my dataset; each row is a visit.
id #<- this is the unique ID for each patient
event #<- this variable tells what type of visit it was
event == 1 #this is a 'well' visit
event == 2 #this is a lab visit 
event == 3 #this is a sick visit
event == 4 #this is an urgent care visit
by(dataset[,"event"], dataset[,"id"], function(dataset) {
nrow(subset(dataset["event"], (dataset["event"]==1 | dataset["event"]==2)))})

事实上,当我分离函数时nrow(subset(dataset["event"], (dataset["event"]==1 | dataset["event"]==2)))

by声明中,我得到了所有患者的这些类型就诊的总数。当我运行包含by语句的代码时,我得到了id的分隔,但值为NULL。我很确定这个问题是我的function()代码中缺少的。。。

提前感谢您的帮助!

table(subset(dataset, event %in% c(1, 2))$id)

最新更新