purrr::pluck() 和 purrr::map() 的第二个参数类型为 double。

huangapple go评论71阅读模式
英文:

purrr::pluck() and purrr::map() with second argument of type double

问题

这与《Advanced R》中的第9.2.6章,练习2有关,由Hadley Wickham编写。

我无法解释purrr函数pluck()map()与第二个参数中的某些双精度值组合的行为。

# 使用双精度索引的 pluck()
pluck(1:3, -2.3456)   # 返回 1
pluck(1:3, 2.9876)    # 返回 2

# 使用双精度向量的 map()
map(1:3, runif(2))    # 返回 list(1, 2, 3)

为什么我们会得到这些结果?

英文:

This is related to Chapter 9.2.6, Exercise 2 in Advanced R by Hadley Wickham.

I cannot explain the behavior of the purrr functions pluck() and map() in combination with certain double values in the second argument.

# pluck with index of type `double`
pluck(1:3, -2.3456)   # returns 1
pluck(1:3, 2.9876)    # returns 2

# map with vector of type `double`
map(1:3, runif(2))    # returns list(1, 2, 3)

Why do we get these results?

答案1

得分: 2

For your first example pluck(1:3, -2.3456), 如果看 pluck 的 C 源代码,它包含以下代码:

if (val < 0) {
      val = n + val + 1;
    }

所以对于负索引,它会从总元素数量中减去该值,并加上 1。这是有道理的,例如,如果您要查找三个元素列表的索引 -2(从右边数第二个),它将查找索引 3 + -2 + 1,结果为 2(从右边数第二个)。对于您的示例,它将是 3 + -2.3456 + 1 = 1.6544。

对于 pluck(1:3, 1.6544),结果为 1,因为 pluck 模拟 [[,根据 R 文档 进行非整数索引时:非整数值在使用之前被转换为整数(向零截断)。

类似地,对于您的第二个示例,2.9876 被截断为 2。

关于您的第三个示例,我不了解。

英文:

For your first example pluck(1:3, -2.3456), if you look at the c source code of pluck it has

if (val < 0) {
      val = n + val + 1;
    }

So for negative indexes, it subtracts the value from the total number of elements and adds 1. This makes sense, for example if you are looking for index -2 (second from the right) of a three element list, it would look for index 3 + -2 + 1, which equals 2 (the second from the right). For your example it would be 3 + -2.3456 + 1 = 1.6544

pluck(1:3, 1.6544) is 1, because pluck emulates [[ and per The R documentation when you index with non-integer values: Non-integer values are converted to integer (by truncation towards zero) before use.

Similarly for your second example, 2.9876 gets truncated to 2.

I don't know about your third example.

huangapple
  • 本文由 发表于 2023年5月21日 04:14:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定