【问题标题】:How to use apply function and which function of apply-family?如何使用apply函数以及apply-family的哪个函数?
【发布时间】:2013-02-27 15:23:21
【问题描述】:

我仍在为不同的 apply 函数以及它们如何替换 for-next 循环而苦苦挣扎。我想要做的是根据值的排序顺序对带有字符串(值标签)的向量进行排序,在我的例子中是优势比。

我在“oo”对象中有优势比(无序),在 so 对象中有排序/有序的优势值。此外,我的值标签按与“oo”相同的顺序排序,现在应该重新排序以匹配“so”对象中的值:

# sort labels descending in order of
# odds ratio values
oo <- exp(coef(x))[-1]
so <- sort(exp(coef(x))[-1])
nlab <- NULL
for (k in 1:length(categoryLabels)) {
  nlab <- c(nlab, categoryLabels[which(so[k]==oo)])
}
categoryLabels <- nlab

例如

  • “oo”为 (0.3, 0.7, 0.5)
  • “所以”是 (0.3, 0.5, 0.7)
  • categoryLabels (of oo) 是 ("A", "B", "C"),应该按照 "so" 重新排序:("A", "C", "B")

我想知道的是,是否可以将 for-next-loop 替换为 apply-function,如果可以,如何?

提前致谢, 丹尼尔

【问题讨论】:

  • categoryLabels 元素的顺序是否与 oo 元素开头的顺序相同?如果是这样,ord &lt;- order(00) 后跟 so &lt;- oo[ord]categoryLabels &lt;- categoryLabels[ord] 应该这样做。最好将oo 转换为named 向量,并将names 属性设置为categoryLabels,然后对oo 进行排序。当然,这是我在本评论第一句话中询问的假设。
  • "categoryLabels 元素的顺序是否与 oo 元素开始的顺序相同?" - 是的,“oo”是包含 OR 值的“原始赔率”,类别标签与这些 OR 相关(即相同的“无序”顺序)。 “所以”应该是“排序的赔率”。 order 函数运行良好,我使用了 David 建议的实现。

标签: r apply


【解决方案1】:

看起来您要做的只是根据oo 订购categoryLabels,这可以通过以下方式完成:

categoryLabels = categoryLabels[order(oo)]

order 为您提供一个索引向量,当用于索引向量时,会将其转换为排序顺序。在您的示例中:

oo = c(0.3, 0.7, 0.5)
order(oo)
# [1] 1 3 2

虽然如果我们确实以sooo 开头,但在这种情况下使用match 比使用任何apply 函数要容易得多:

categoryLabels = categoryLabels[match(oo, so)]

match 是一个函数,它在第二个向量中找到第一个向量的索引。在您的示例中:

oo = c(0.3, 0.7, 0.5)
so = c(0.3, 0.5, 0.7)
match(oo, so)
# [1] 1 3 2

【讨论】:

  • 谢谢你,大卫!工作正常,我再次深入了解 R 语法和编码!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-17
  • 2016-04-29
相关资源
最近更新 更多