TheSciGuy
TheSciGuy

Reputation: 1196

Create new column based on ending of character string in R

I would like to create a new column Trial based on the ending of a character string. For example, the characters that end with the number 2 like A3-H2 or A9-H2 will be considered Trial 2 and those not ending with a number like A3-H or A9-H will be considered Trial 1. This should be an easy ifelse statement but I don't know how to do it based on the end of a character string.

It would go from this:

      Plant     Trtmt    
1:     SC       A3-H
2:     SC       A3-H2
3:     SC       A9-H
4:     SC       A9-H2

To this:

      Plant     Trtmt    Trial
1:     SC       A3-H       1
2:     SC       A3-H2      2
3:     SC       A9-H       1
4:     SC       A9-H2      2

Real Data:

dput(stack.df)
structure(list(Plant = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("SC", 
"W"), class = "factor"), Trtmt = c("A3-H", "A3-H", "A3-H", "A3-H", 
"A3-H", "A9-H", "A9-H", "A9-H", "A9-H", "A9-H", "A3-H2", "A3-H2", 
"A3-H2", "A3-H2", "A3-H2", "A9-H2", "A9-H2", "A9-H2", "A9-H2", 
"A9-H2")), .Names = c("Plant", "Trtmt"), row.names = c(6L, 7L, 
8L, 9L, 10L, 16L, 17L, 18L, 19L, 20L, 66L, 67L, 68L, 69L, 70L, 
76L, 77L, 78L, 79L, 80L), class = "data.frame")

Upvotes: 2

Views: 1736

Answers (4)

akrun
akrun

Reputation: 887971

Here is one option with str_extract

library(stringr)
library(data.table)
setDT(stack.df)[, Trial := pmax(as.numeric(str_extract(Trtmt, "\\d+$")), 1, na.rm = TRUE)]

Upvotes: 2

mysteRious
mysteRious

Reputation: 4314

library(dplyr)
library(stringr)
stack.df %>% mutate(Trial = ifelse(str_sub(Trtmt,-1)=="2", 2, 1))

Upvotes: 3

neilfws
neilfws

Reputation: 33822

library(tidyverse)

stack.df <- stack.df %>% 
  mutate(Trial = ifelse(grepl("2$", Trtmt), 2, 1))

Upvotes: 3

Pdubbs
Pdubbs

Reputation: 1987

You can get the last character with substr(stack.df$Trtmt,nchar(stack.df$Trtmt)-1,nchar(stack.df$Trtmt))

Like you said, it's an easy ifelse from there :-)

Upvotes: 1

Related Questions