简体   繁体   中英

How to use query function of hashmap in mutate of dplyr pipe in R?

I would like to find a value using a hashmap and then use this value to calculate a new one. Usually I try to work efficiently, but I am not very proficient in R. I know the basics of dplyr pipes, so do no longer want to use for loops.

Here is a minimal reproducable example of the situation:

data("mtcars")

m.subset <- mtcars[2:7, 10:11]
letters <- c("a", "b", "c", "d", "e", "f")
m.subset <- cbind(m.subset, letters)

testmap <- hashmap()
testmap[c("a", "b", "c", "d", "e", "f")] <- c(4.0, 5.0, 6.0, 7.0, 8.0, 9.0)

m.subset %>% mutate(score1=query(testmap, letters)*gear) -> m.subset

Unfortunately, I get this error:

Error in `mutate()`:
! Problem while computing `score1 = query(testmap, letters) * gear`.
✖ `score1` must be size 6 or 1, not 0.
Run `rlang::last_error()` to see where the error occurred.

A note is that this works: score1=query(testmap, m.subset$letters[1])*m.subset$gear[1] , where I can obviously interchange the 1 with an i and use a for loop. But I prefer not to, as a dplyr pipe is so nice to do columnwise calculations.

I also read several questions on StackOverflow, like error-in-r-mutate-must-be-size-4-or-1-not-0 .

Assuming you are using r2r for hashmap and query , you can try the following. Using map2 from purrr you can go through each element of letters and gear , and apply the function query using your testmap .

library(tidyverse)
library(r2r)

m.subset %>% 
  mutate(score1 = map2(
    letters,
    gear,
    ~ query(testmap, .x) * .y
  ))

Output

                  gear carb letters score1
Mazda RX4 Wag        4    4       a     16
Datsun 710           4    1       b     20
Hornet 4 Drive       3    1       c     18
Hornet Sportabout    3    2       d     21
Valiant              3    1       e     24
Duster 360           3    4       f     27

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM