【问题标题】:Identify which element is being processed when using *apply functions识别使用 *apply 函数时正在处理的元素
【发布时间】:2012-03-23 04:06:16
【问题描述】:

大概 R 在运行 *apply 函数时知道它正在处理列表的哪个成员、向量的元素或矩阵的行等。是否可以在函数中使用此索引,而无需采取类似的解决方法:

fruit <- c("Bananas", "Oranges", "Avocados", "Celeries?")
sapply(fruit, function(x) 
   paste(x, "are fruit number", which(fruit==x)))

或其他解决方法,例如 these 发布参考类似问题?

希望 [徒劳无功?] 更优雅的东西。

【问题讨论】:

标签: r


【解决方案1】:

我宁愿写

sapply(seq_along(fruit), function(ii) paste(fruit[ii], "are fruit number", ii))

【讨论】:

  • seq_along() 本质上只是1:length(fruit) 的简写吗?那么,seq_along 的优势是primitive,因此速度很快。但最终这是否不仅使 *apply 成为更明确的for 循环?我想我对便利循环函数的期望太高了,应该尝试矢量化!
  • 如果不是那些爱管闲事的孩子,他可能会侥幸逃脱。
  • seq_along 也更健壮一些,试试fruit = c(); seq_along(fruit); 1:length(fruit)。我同意for 循环是一个有效的选择,在给定情况下更清晰的我会更喜欢。
【解决方案2】:

您可以将索引而不是向量传递给 sapply;

fruit <- c("Bananas", "Oranges", "Avocados", "Celeries?")
sapply(seq_along(fruit), function(x) paste(fruit[x], "are fruit number", x))

【讨论】:

  • 通过洗礼节拍 30 秒
  • 下次选短名字的水果:-)
  • 我很失望没有人注意到芹菜不是水果,而是茎。
  • 有趣的是,我跑得这么快,我的大脑注册为樱桃。
【解决方案3】:

也许 mapply 是一个有用的选择? (不过这里并不需要)

fruit <- c("Bananas", "Oranges", "Avocados", "Celeries?")
mapply(paste, fruit, "are fruit number", seq_along(fruit))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多