Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

Custom lookup function in R not working within dplyr::mutate in R

$
0
0

I'm trying to use a custom function, which filters a dataframe and pulls information from another column, within dplyr::mutate with dplyr version 0.8.3. I'm getting two types of errors. One with a large dataframe yields Error: Result must have length 32, not 1728 as an error and the other, used in the following example code, does not return an error message but returns a wrong match.

Lookup Dataframe

lookup.df<-data.frame(to.match=paste(letters[1:7],letters[8:14],sep = ""),
                       match=c("one","two","three","four","five","six","seven"))

lookup.df

  to.match match
1       ah   one
2       bi   two
3       cj three
4       dk  four
5       el  five
6       fm   six
7       gn seven

Lookup Fucntion

lookup_function<-function(x){
  y<-lookup.df %>% 
    mutate_all(as.character) %>% 
    filter(to.match==x) %>% 
    pull(match)
  y
}

Vectorize(lookup_function)

Terminal Run

Running the function from the terminal does return the expected results.

> lookup_function("dk")
[1] "four"> lookup_function("el")
[1] "five"

dplyr::mutate Run

Running the same function to a diffrent dataframe within dplyr::mutate does not return the expected results.

 live.df<-data.frame(to.match=rev(paste(letters[1:7],letters[8:14],sep = "")))

 live.df %>% 
   mutate(live.match=lookup_function(to.match))

  to.match live.match
1       gn       four
2       fm       four
3       el       four
4       dk       four
5       cj       four
6       bi       four
7       ah       four

The code should, in this example at least, should return the match column of the lookup.df but reversed but it instead returns four in every row.

Vector through Sapply

The function does seem to return the appropriate results when piped through sapply.

c("dk","el") %>% sapply(lookup_function)
    dk     el 
"four""five"

I'm barely familiarized with Vectorization of cutom functions for this type of use so I'm unsure if that is the source of this error.

What would be the propper way to fix this custom function so that it returns the correct information from the lookup dataframe?


Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>