Home > Back-end >  R dplyr mutate: creating one variable from multiple column variables using "or" logic
R dplyr mutate: creating one variable from multiple column variables using "or" logic

Time:01-09

I am trying to do something that I think is straightforward but I am having an issue with.

I have several medication-related column headings (med_1, med_2, med_3 for example). I want to combine them all into variable anymed using or logic, so that I can then use anymed to look at any medications reported across all medication related fields. The fields are text-based.

I am trying the following, for dataset FinalData.

FinalData <- FinalData %>% mutate(anymed = med_1 | med_2 | med_3)

I am receiving this error:

*Error: Problem with `mutate()` column `anymed`.
ℹ `anymed = |...`.
x operations are possible only for numeric, logical or complex types*

Could someone help explain what code I should use instead?

CodePudding user response:

You want to use pivot_longer from tidyverse to get them all in the same column. I also dropped the column name (i.e., col), but you could remove that line if you want to know what column the medication came from. I'm unsure what your data looks like, so I just made a small example to show how to do it.

library(tidyverse)

FinalData %>%
  pivot_longer(-ind, names_to = "col", values_to = "anymed") %>%
  select(-col)

Output

# A tibble: 6 × 2
    ind anymed
  <dbl> <chr> 
1     1 meda  
2     1 meda  
3     1 meda  
4     2 medb  
5     2 medb  
6     2 medb  

Data

FinalData <-
  structure(
    list(
      ind = c(1, 2),
      med_1 = c("meda", "medb"),
      med_2 = c("meda",
                "medb"),
      med_3 = c("meda", "medb")
    ),
    class = "data.frame",
    row.names = c(NA,-2L)
  )

CodePudding user response:

Are you looking for this kind of solution:

# data:
df <- tibble(med_1 = "A", med_2 = "B", med_3 = "C")

library(dplyr)
df %>% 
  mutate(any_med = paste(c(med_1, med_2, med_3), collapse = " | "))
  med_1 med_2 med_3 any_med  
  <chr> <chr> <chr> <chr>    
1 A     B     C     A | B | C
  •  Tags:  
  • Related