Michael
Michael

Reputation: 575

Create new column if first letter is a specific letter in R

Consider the following data in R:

d <- data.frame(a = c("E5","E5","E5","E5"),
                b = c("011","012","013","111"))

I want to add a new column that is equal to "A5" if the first letter in column b is 0 excerpt "013". That is, I want the following table:

    a   b    c  
1   E5  011  A5
2   E5  012  A5
3   E5  013
4   E5  111  

How do I do that in R?

Upvotes: 1

Views: 247

Answers (2)

akrun
akrun

Reputation: 887028

An option with data.table

library(data.table)
setDT(d)[substr(b, 1, 1) == 0 & b != '013', c := 'A5']

-output

d
#    a   b    c
#1: E5 011   A5
#2: E5 012   A5
#3: E5 013 <NA>
#4: E5 111 <NA>

Upvotes: 1

Karthik S
Karthik S

Reputation: 11584

Does this work:

> d
   a   b
1 E5 011
2 E5 012
3 E5 013
4 E5 111
> transform(d, c = ifelse(str_detect(d$b, '^01[^3]'), 'A5',''))
   a   b  c
1 E5 011 A5
2 E5 012 A5
3 E5 013   
4 E5 111   
> 

Upvotes: 1

Related Questions