Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add brackets to string in data frame

Tags:

r

rscript

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?

like image 385
TityBoi Avatar asked Jun 15 '26 18:06

TityBoi


1 Answers

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)"
like image 113
Ronak Shah Avatar answered Jun 17 '26 06:06

Ronak Shah