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

R "by" function returning NULL values when paired with self-created "nrow" function

我确实花了超过 3 个小时来解决这个问题。我正在尝试获取每个 ID 的实例数。我在 "by" 函数中创建了自己的函数并测试了该函数,它为我提供了所有 id 组合的正确计数...但是当我 运行 下面的代码:

为了使它成为一个更实用的概念.. 如果我想知道每个病人在我的设施中有多少次 "well" + "lab" 就诊怎么办? :

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)