【发布时间】:2020-06-14 04:04:05
【问题描述】:
我有一个列表,我需要将具有不同索引的元素相加。我正在苦苦挣扎,因为我想在不同的索引处创建一个循环。
data(aSAH)
rocobj <- roc(aSAH$outcome, aSAH$s100b)
dat<-coords(rocobj, "all", ret=c("threshold","sensitivity", "specificity"), as.list=TRUE)
我想创建一个函数,我可以在其中查看新数据框中所有阈值处的所有sensitivity/1-specificity 组合。我知道阈值在dat[1,],敏感性在dat[2,],特异性在dat[3,]。所以我尝试了:
for (i in length(dat)) {
print(dat[1,i]
print(dat[2,i]/(1-dat[3,i]))
}
我最终应该得到一个包含threshold 和sensitivity/1-specificity 的数据框。
数据
dput(head(aSAH))
structure(list(gos6 = structure(c(5L, 5L, 5L, 5L, 1L, 1L), .Label = c("1",
"2", "3", "4", "5"), class = c("ordered", "factor")), outcome = structure(c(1L,
1L, 1L, 1L, 2L, 2L), .Label = c("Good", "Poor"), class = "factor"),
gender = structure(c(2L, 2L, 2L, 2L, 2L, 1L), .Label = c("Male",
"Female"), class = "factor"), age = c(42L, 37L, 42L, 27L,
42L, 48L), wfns = structure(c(1L, 1L, 1L, 1L, 3L, 2L), .Label = c("1",
"2", "3", "4", "5"), class = c("ordered", "factor")), s100b = c(0.13,
0.14, 0.1, 0.04, 0.13, 0.1), ndka = c(3.01, 8.54, 8.09, 10.42,
17.4, 12.75)), .Names = c("gos6", "outcome", "gender", "age",
"wfns", "s100b", "ndka"), row.names = 29:34, class = "data.frame")
编辑 一个答案:
dat_transform <- as.data.frame(t(dat))
dat_transform <- dat_transform %>% mutate(new=sensitivity/(1-specificity))
【问题讨论】:
-
为什么
i在两个循环中都重复了? -
我不太确定,我看到了一个与我的问题类似的例子。我更新了功能;我认为这更正确?
-
只需省略
as.list=TRUE(因为您需要数据框,而不是列表)并使用 Ronak 的解决方案。 -
是的,我在没有
as.list参数的情况下尝试了 Ronak 的解决方案,但我仍然收到我在 cmets 下面写的错误