1

I have the following keyvalue dataframe

keyval =  data.frame(key = c('facebook',  'facebook mai - android', 
         'facebook mai - ios', 'facebook remarketing','facebook ig', 
         'app - android', 'bing - sem broad', 'bing - trademark', 
         'google - sem broad' , 'google - trademark' , 'google display', 'pla', 
         'google retargeting') ,
          val = c(6,21,20,7,9,21,5,19,3,17,3,12,4))

and would like to use an ifelse statement to access the value when it corresponds but I'm not sure of how to write the second argument.

the_value_i_want =  ifelse(data$Publisher %in% keyval$key , 
                            notsurehowtowrite this part ,'error'), 
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
teo93
  • 129
  • 3
  • 12
  • Possible duplicate https://stackoverflow.com/questions/5577727/is-there-an-r-function-for-finding-the-index-of-an-element-in-a-vector – Ronak Shah Apr 24 '18 at 04:47

2 Answers2

1

I think ifelse is not needed.

Subset data by the results of data$Publisher %in% keyval$key:

data[ data$Publisher %in% keyval$key, ]

This will return all the rows matching Publisher in key.

edit: Because your question is a bit unclear, you might want just the value instead of the whole data frame. If this is the case then:

data[data$Publisher %in% keyval$key,]$val

will return the val variable.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
Amar
  • 1,340
  • 1
  • 8
  • 20
1

We can also use match; here is an example:

# Sample data
data <- cbind.data.frame(Publisher = c("facebook", "google display", "other"));

data$the_value_i_want <- keyval$val[match(data$Publisher, keyval$key)];
data;
#       Publisher the_value_i_want
#1       facebook                6
#2 google display                3
#3          other               NA
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
  • currently having this error though Error in mutate_impl(.data, dots) : Evaluation error: object of type 'closure' is not subsettable. – teo93 Apr 24 '18 at 05:45
  • 1
    @teo93 I'm not using `mutate` (or any `tidyverse`/`dplyr` function) anywhere; so your error originates from somewhere else, and has nothing to do with the base R code above. – Maurits Evers Apr 24 '18 at 05:56