【问题标题】:combine multiple elements in a list with different indexes in r将列表中的多个元素与 r 中的不同索引组合起来
【发布时间】: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]))
}

我最终应该得到一个包含thresholdsensitivity/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 下面写的错误

标签: r list loops


【解决方案1】:

你可以使用:

transform(t, res = sensitivity/(1-specificity))[c(1, 4)]

或者dplyr

library(dplyr)

t %>%
  mutate(res = sensitivity/(1-specificity)) %>%
  select(threshold, res)

另请注意t 是 R 中用于转置数据帧的默认函数,因此最好为数据帧使用其他变量名。

【讨论】:

  • 感谢您的精彩提示:t。不幸的是,我收到了两种解决方案的错误消息:Error in sensitivity/1 : non-numeric argument to binary operatorError in UseMethod("mutate_") : no applicable method for 'mutate_' applied to an object of class "c('matrix', 'double', 'numeric')"。我认为第一个是指敏感性和特异性是字符,但它说我不能使用as.numeric 更改它们,因为它们是向量。 t 是双精度,所以我使用 t&lt;-lapply(t, as.numeric) 将其更改为列表,但这也不会使选项 2 起作用
  • 这很奇怪,这对我有用,因为它适用于共享数据。对于错误Error in sensitivity/1 : non-numeric argument to binary operator,这意味着您的数据属于非数字类,第二个错误表明t 是一个矩阵。您可以将其转换为数据框,然后重试。
  • 我还是有问题。我rm()我所有的功能和数据并再次尝试了这两种解决方案,但我仍然遇到错误。我将矩阵转换为数据框并得到错误 Error: Columns all, all, all,... 。我在coords 函数中添加了附加参数(更新了问题); str() 表明它都是数字但解决方案 1 也不起作用。有什么想法吗?
  • @PleaseHelp 你能和dput分享你正在使用的数据吗? dput(head(aSAH)) ?让我看看我是否可以在最后重现同样的错误。
  • 我试用了您的解决方案并得到了另一个解决方案,并将其添加到我的帖子中。但是你能帮我理解为什么你的两个原始解决方案不能让我学习吗?它们似乎是优雅的解决方案!
猜你喜欢
  • 2017-12-26
  • 2021-05-09
  • 1970-01-01
  • 2020-01-27
  • 1970-01-01
  • 1970-01-01
  • 2011-04-30
  • 1970-01-01
  • 2016-02-11
相关资源
最近更新 更多