【发布时间】:2019-09-15 07:07:17
【问题描述】:
我需要计算一名工人的特定岗位和轮班前测量值的差异,并将这两个差异取平均值。一个差异是 9,另一个是 -2,但是当我使用“平均值”来计算平均值时,R 显示的是 9 而不是 4.5。我究竟做错了什么。我的代码(4和8是post,1和5是pre):
mean((p2res$feno[p2res$no=="4"&p2res$subject.id==4])-
(p2res$feno[p2res$no=="1"&p2res$subject.id==4])+
(p2res$feno[p2res$no=="8"&p2res$subject.id==4])-
(p2res$feno[p2res$no=="5"&p2res$subject.id==4]))
p2res <- structure(list(subject.id = c(4, 4, 4, 4, 4, 4, 4, 4, 6,
6, 6, 6, 6, 6, 6, 6), no = c(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4,
5, 6, 7, 8), feno = c(24, 23, 40, 35, 28, 25, 22, 26, 19, 19, 18,
19, 15, 14, 29, 18)), row.names = c(NA, -16L), class =
c("data.frame"))
subject.id no feno
4 1 24
4 2 23
4 3 40
4 4 35
4 5 28
4 6 25
4 7 22
4 8 26
6 1 19
6 2 19
6 3 18
6 4 19
6 5 15
6 6 14
6 7 29
6 8 18
另外,我怎样才能为其他测量创建一个函数呢?
【问题讨论】:
-
你能和
dput(p2res)分享你的数据吗? -
x
-
我不确定如何向您展示 data.frame,但这就是我从 dput() 得到的
-
@Nilou 这是数据框,现在任何人都可以将其复制/粘贴到 R 中。
-
如果你想要
35 - 24和26 - 28的平均值,那么你不应该将它们加在一起,而是需要将它们连接到一个向量中:mean(c(35 - 24, 26- 28)),或者从数据mean(c(p2res$feno[p2res$no=="4"&p2res$subject.id==4] - p2res$feno[p2res$no=="1"&p2res$subject.id==4], p2res$feno[p2res$no=="8"&p2res$subject.id==4] - p2res$feno[p2res$no=="5"&p2res$subject.id==4]))