I have a named vector which is essentially a lookup table. So the names of each element represent the key, while the element represents a value.
I have a data frame which contains a random sample of the key values which appear in the vector above. My intention is to match the key and obtain the value for each key.
It is easy to accomplish by using mutate from the dplyr package. However, in the lookup process, I get an error if I try to use [[ instead of [. My understanding is that for vectors both the functions should return back a vector.
Can someone please explain why this happens? A minimum reproducible example is below.
x <- c("1" = "a", "2" = "b", "3" = "c")
df <- data.frame(
k = sample(c(1, 2, 3), 10, replace = TRUE),
v = rnorm(10)
)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
df %>%
mutate(k2 = x[k])
#> k v k2
#> 1 1 -0.7502716 a
#> 2 1 -0.4002250 a
#> 3 1 0.4878860 a
#> 4 2 1.2878120 b
#> 5 3 0.6410854 c
#> 6 3 -0.6821807 c
#> 7 1 1.4106239 a
#> 8 3 0.9909921 c
#> 9 2 0.3808955 b
#> 10 3 1.6117826 c
df %>%
mutate(k2 = x[[k]])
#> Error in x[[k]]: attempt to select more than one element in vectorIndex
k <-
instead ofk=
orv=
– akrunx[[i]]
,i
should have length of one, as explained by the error. Also, yeah, your columns have gibberish names for the reason akrun mentioned. – Frank