【发布时间】:2019-12-04 03:34:46
【问题描述】:
我正在尝试制作包含事件和时间的生存数据集。
数据集被重复评估四次。 firs 表示第一次观察,seco 表示第二次观察……以此类推。
事件定义为观察值成为第一次观察的一半。
时间是事件发生的时间,所以如果firs中的5变成thir中的2,时间就是3。
如果直到四点才发生事件,则事件为 0,时间为 4。
如果发生丢失,则事件为 0,时间为该时间。
set.seed(1234)
firs<-sample(x=1:10,size=10)
seco<-sample(x=1:10,size=10)
thir<-sample(x=1:10,size=10)
four<-sample(x=1:10,size=10)
set<-as.data.frame(cbind(firs,seco,thir,four))
set$crit<-set$firs/2
set[2,3]<-NA
set[9,2]<-NA
set
firs seco thir four crit
1 2 7 4 5 1.0
2 6 5 NA 3 3.0
3 5 3 2 9 2.5
4 8 10 1 4 4.0
5 9 2 8 2 4.5
6 4 9 5 7 2.0
7 1 6 9 1 0.5
8 7 1 10 10 3.5
9 10 NA 6 6 5.0
10 3 4 7 8 1.5
所以,在这个数据集中,时间和事件将是
time event
1 4 0
2 3 0
3 3 1
4 3 1
5 2 1
...等等
我正在尝试使用 for 和 if 语句编写代码。但是,它产生了错误。
例如,
for(i in 2:4){
if(set[,i]<set$crit){
set$event<-1
set$time<-i-1
}else if(set[,i]>set$crit)
{set$event<-0
set$time<-i}
}
Warning messages:
1: In if (set[, i] < set$crit) { :
the condition has length > 1 and only the first element will be used
2: In if (set[, i] > set$crit) { :
the condition has length > 1 and only the first element will be used
3: In if (set[, i] < set$crit) { :
the condition has length > 1 and only the first element will be used
4: In if (set[, i] > set$crit) { :
the condition has length > 1 and only the first element will be used
5: In if (set[, i] < set$crit) { :
the condition has length > 1 and only the first element will be used
6: In if (set[, i] > set$crit) { :
the condition has length > 1 and only the first element will be used
能否告诉我问题出在哪里以及如何解决?
【问题讨论】:
-
长度大于1
if(set[,i]<set$crit你可能需要ifelse -
对于 4 列,为什么您预期只有一个“事件”列。你需要
rowSums(set[1:4] < set$crit[col(set[1:4])], na.rm = TRUE) -
@akrun(抱歉 ctrl+k 在 chrome 中的注释中不起作用)我编写了如下代码,但错误再次出现。你能告诉我是什么问题吗? for(i in 2:4){ ifelse(set[,i]
set$crit ) {set$event -
这是关于生存分析的“发生率”。生存分析是关于最早的事件及其时间。最早的事件会被审查。
标签: r for-loop if-statement