Comparing character columns - using & operations

Hi,

I am wondering how I might set about comparing characters/words and creating new results depending on the values.

My test example, which doesn't work, is as follows:

library(tidyverse)

#Create a new variable
number <- c("one","two","three","four","five")
chr_columns <- tibble(number)

# A tibble: 5 × 2
  number total
  <chr>  <chr>
1 one    
2 two    
3 three  #Five
4 four   
5 five  

My non functioning code is below.

chr_columns <- chr_columns %>%
  mutate(total = case_when(
    number="three" & number="two" %in% number ~ "Five"
  ))
head(chr_columns)

I have searched high and low, and I'm stuck, though I can only imagine there's a far more effective way to approach this problem? FWIW I only plan on using 'And' comparisons. I could convert the words to numbers, but this feels like more of a challenge.

Any advise much appreciated!

To fix the immediate problem with your code, you can use the following:

library(tidyverse)
number <- c("one","two","three","four","five")
chr_columns <- tibble(number)
chr_columns <- chr_columns %>%
   mutate(total = case_when(
     "three" %in% number & "two" %in% number ~ "Five"
   ))
head(chr_columns)
# A tibble: 5 x 2
  number total
  <chr>  <chr>
1 one    Five 
2 two    Five 
3 three  Five 
4 four   Five 
5 five   Five

I do not understand your goal. Does it make sense to put "Five" in every row? Can you explain more about what you want to accomplish?

reading between the lines, I would wager that he's looking for something related to adjacency as an aspect.
I think this is implied because in his example he only marks five against the three

library(tidyverse)

chr_columns <- tibble(number= c("one","two","three","four","five"))

 chr_columns %>%
   mutate(
    total = case_when(
     "three" == number & "two"== dplyr::lag(number) ~ "Five"
   ))
1 Like

That's exacty what I needed, thank you very much indeed!

Thanks for your reply, and apologies, my example was somewhat incomplete!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.