Assign a new variable based on existing variable's value

In dataset below, I want to assign a new variable msr_set based on msr_cd. if the msr_cd=='Eng-1', msr_set='Eng'... The msr-cd is in dynamic length and value like Meth-02, Eco-01...,but the patter of it is the same. The msr_set is the prefix of the hyphen '-' in msr_cd. Is there a better way to do? Thanks!

try <- data.frame(
stringsAsFactors = FALSE,
msr_cd = c("Meth-1", "Eng-1", "Eng-1", "Art-5", "Art-5"),
rpt_yr = c(2022, 2022, 2022, 2022, 2022),
rpt_mo = c(1, 2, 3, 1, 2)
)

Try

library(tidyverse)
try <- try |> mutate(msr_set = str_extract(msr_cd,"\\w+"))

The latter matches any number of letters or numbers.

1 Like

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.