1
votes

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
1
It is because you used a different operator for assignment inside the data.frame k <- instead of k= or v=akrun
With x[[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

1 Answers

2
votes

We can use [ instead of [[ as @Frank mentioned about difference in length of input argument it takes ([[ - works with length of 1 while [ works for 1 or more) and match the names of 'x' by converting the 'k' to character class and get the values from 'x' to create 'k2' (assuming that we want the values for matching names and not based on numeric index)

df %>%         
    mutate(k2 =  x[as.character(k)])