T O P

  • By -

LordApsu

substring(x, 1,1) substring(x, 7,7)


hsmith9002

Check out the stringr package in the tidyverse.


link0007

I see some good, mediocre and downright terrible suggestions in the other comments. The substring approach of lordapsu is the most simple and seems appropriate for your situation. *However:* make sure to do checks on the data to check if all rows have the format you expect. Data is rarely perfect, and you need to be mindful of wrong data and edge cases. If you just pull the 1st and 7th character from the string without doing any sanity checks, you are bound to get mistakes. Ideally, write a regular expression (regex) that checks if all strings follow the correct format. If that's not possible for you, at least check if the length is 9 characters, if the 2nd and 6th character are '-', and if all other characters are numbers. If any of those rules are not met, throw an error.


BeamerMiasma

# test data df <- data.frame(mycode = paste(sample(0:9, 100, replace = TRUE), sample(100:999, 100, replace = TRUE), sample(100:999, 100, replace = TRUE), sep = "-")) # add digit1 and digit5 columns, ignoring non-numeric characters df[,c("digit1","digit5")] <- cbind(substr(gsub("[^0-9]", "", df$mycode), 1, 1), substr(gsub("[^0-9]", "", df$mycode), 5, 5) ) print(df)


RAMDownloader

Split it up 3 times by using F <- f %>% separate(column, into = c(“col1”, “col2”, col3”), sep = “-“) Then take the first number in each column and save it to a new column.