TityBoi TityBoi - 3 months ago 12
R Question

Add brackets to string in data frame

I've got this data frame called df:

ColumnA ColumnB
String1 A
String2 A
String3 B
String4 A
... ...


Every string in ColumnA have different lenght. I want to put values from ColumnA in brackets if value in ColumnB == A in the same row. If the value in ColumnB == B I want to add square brackets instead. So it will looks like:

ColumnA ColumnB
(String1) A
(String2) A
[String3] B
(String4) A
... ...


What's the best way to achive that?

Answer

You can use ifelse

df1$ColumnA <- with(df1, ifelse(ColumnB == "A", paste0("(", ColumnA, ")"), 
                                                    paste0("[", ColumnA, "]")))
> df1$ColumnA

#[1] "(String1)" "(String2)" "[String3]" "(String4)"

Or if there are values other than A and B in ColumnB, you can use multiple ifelse

df1$ColumnA <- with(df1, ifelse(ColumnB == "A", paste0("(", ColumnA, ")"), 
                       ifelse(ColumnB == "B", paste0("[", ColumnA, "]"), ColumnA)))
> df1$ColumnA

#[1] "(String1)" "(String2)" "[String3]" "(String4)"
Comments