【发布时间】:2018-09-23 03:39:24
【问题描述】:
我正在尝试将我的原始数据转换为 Cox 回归的启停格式。我原来的数据集是这样的:
df = data.frame(initial = c(25, 25, 20, 21, 21, 17),
total = c(4.25, 28, 0.5, 38, 14, 43),
age = c(30, 53, 20, 59, 35, 60),
ethanol = c(0.04, 0.306, 0.201, 0.222, 0.047, 0.085),
status = c(0, 0, 0, 0, 0, 1))
例如,对于第一次观察,原始数据格式是这样的:
initial total age ethanol status
1 25 4.25 30 0.04 0
预期的数据格式如下:
id start stop ethanol status
1 0.00 25.00 0.00 0
1 25.00 29.25 0.04 0
1 29.25 30 0 0
所以我写代码如下
edf = data.frame(id = integer(),
start = numeric(),
stop = numeric(),
ethanol = numeric(),
status = integer())
j = 1
for( i in 1:4){
if( (df[i, 1] + df[i,2]) >= df[i,3] ){
edf[j,1] = i
edf[j,2] = 0
edf[j,3] = df[i,"initial"]
edf[j,4] = 0
edf[j,5] = 0
j = j+1
edf[j,1] = i
edf[j,2] = df[i,"initial"]
edf[j,3] = df[i,"initial"] + df[i,"total"]
edf[j,4] = df[i,"ethanol"]
edf[j,5] = df[i,"status"]
} else{
edf[j,1] = i
edf[j,2] = 0
edf[j,3] = df[i,"initial"]
edf[j,4] = 0
edf[j,5] = 0
j = j+1
edf[j,1] = i
edf[j,2] = df[i,"initial"]
edf[j,3] = df[i,"initial"] + df[i,"total"]
edf[j,4] = df[i,"ethanol"]
edf[j,5] = 0
j = j+1
edf[j,1] = i
edf[j,2] = df[i,"initial"] + df[i,"total"]
edf[j,3] = df[i,"age"]
edf[j,4] = 0
edf[j,5] = df[i,"status"]
}
}
但是我得到的数据框是(比如第一次观察):
id start stop ethanol status
1 0.00 25.00 0.00 0
1 25.00 29.25 0.04 0
缺少一行:
id start stop ethanol status
1 29.25 30 0 0
似乎else-statement的最后一部分没有执行:
j = j+1
edf[j,1] = i
edf[j,2] = df[i,"initial"] + df[i,"total"]
edf[j,3] = df[i,"age"]
edf[j,4] = 0
edf[j,5] = df[i,"status"]
我不知道怎么了,有什么建议吗? 我在 MacOS 上使用 R 版本 3.4.4 (x86_64-apple-darwin15.6.0.) 提前致谢!
【问题讨论】:
-
请不要使用图像来传达数据:我不会花时间从一个框架转录成我可以在我的 R 会话中使用的东西。请在您的问题中使用类似于
dput(head(x))的输出(在代码块中)。参考:stackoverflow.com/questions/5963269、stackoverflow.com/help/mcve 和 stackoverflow.com/tags/r/info。 -
谢谢。我已经编辑了帖子,尝试使其可重现。
标签: r for-loop if-statement