Home > database >  How to extract and print values in list with %in% function (in order) on R
How to extract and print values in list with %in% function (in order) on R

Time:03-17

I have a very unique problem that I'd hope would have a solution.

data <- data.frame('col1' = c('hi', 'hey', 'bye', 'cya'))

The data above is simply a column with greeting and leaving values

I have two vectors here.

greet <- c('hey', 'hi')
leave <- c('cya', 'bye')

I've put them in the opposite order as I want to match the order as it shows in the table. Now I apply the function

guesslabel <- function(table, m) {
  data %>% dplyr::mutate(guess = ifelse(col1 %in%(m), m, 'none'))
}

When I run the function as such

guesslabel(data, greet)

I get the following output:

col1: _____ guess:

hey _____ hi

hi _____ hey

bye _____ none

cya _____ none

The output that I want:

col1: _____ guess:

hey _____ hey

hi _____ hi

bye _____ none

cya _____ none

Sorry about the formatting, unsure how to do that. I was just wondering how I'd extract the specific value from the list greet that is being used to filter the column variable. So essentially, the column guess should match with col1 (Ignore the none values as that can be solved later), and I don't want to simply use the value from col1. Any help would be much appreciated.

CodePudding user response:

Maybe you can use match -

library(dplyr)

guesslabel <- function(table, m) {
  table %>% 
    mutate(guess = m[match(col1, m)], 
           guess = tidyr::replace_na(guess, 'none'))
}

guesslabel(data, greet)

#  col1 guess
#1   hi    hi
#2  hey   hey
#3  bye  none
#4  cya  none

guesslabel(data, leave)

#  col1 guess
#1   hi  none
#2  hey  none
#3  bye   bye
#4  cya   cya
  •  Tags:  
  • r
  • Related