gpt4 book ai didi

r - Dplyr 变异 : making the difference between vector to be taken element wise and vectors to be taken as vector

转载 作者:行者123 更新时间:2023-12-04 11:12:57 28 4
gpt4 key购买 nike

我正在使用 dplyr 来操作数据。我有两列:x 和 y。在第三列(例如 z)中,我希望所有 x 列中的第一个索引为 y。

例如:

enter image description here

对于第一行,我得到 4,因为 7 在 x 中处于第 4 个位置。

所以我试过了

df <- df %>% 
mutate(z = which (x==y)[1])

但是比较是按元素进行的(即我在 z 中只得到五)。因此我的问题是:如何在 dplyr mutate 中区分元素明智的向量和作为向量的向量?

最佳答案

dplyr 不决定函数是否按元素应用。 mutate 仅提供一种语法,通过识别如果您在 mutate 中引用 x,您可能指的是该列,从而让您更简洁地使用其他函数df$xdf 中。它还执行一个简单的广播步骤,如果您为其提供一个仅返回单个值的函数,它会将其复制到整个输出。

我们可以在下面的 dplyr 之外使用 whichmatch 显示相同的行为。因为 == 进行逐元素比较,所以您的第一个方法返回所有 5match 另一方面,“返回第一个参数在第二个参数中的(第一个)匹配位置的向量”(来自文档),这就是您想要的。我在底部比较了两种语法,以表明关键是您提供的决定如何读取输入的函数,而不是 mutate

x = c(1,2,3,7,9)
y = c(7,3,9,1,9)

x == y
#> [1] FALSE FALSE FALSE FALSE TRUE
which(x == y)
#> [1] 5

match(y, x)
#> [1] 4 3 5 1 5

library(dplyr)
df <- data.frame(x, y)
df$z1 = match(df$y, df$x) # a base R syntax that forces you to specify the data frame name
df <- df %>% mutate(z2 = match(y, x)) # dplyr syntax that is more concise
df # they produce the same result
#> x y z1 z2
#> 1 1 7 4 4
#> 2 2 3 3 3
#> 3 3 9 5 5
#> 4 7 1 1 1
#> 5 9 9 5 5

reprex package 创建于 2018-06-29 (v0.2.0).

关于r - Dplyr 变异 : making the difference between vector to be taken element wise and vectors to be taken as vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51103713/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com