MrMsarguru
MrMsarguru

Reputation: 125

adding special characters and merge the values in a dataframe R

Is is possible to add special characters and paste multiple columns in to a single column

For instance

col1 col2 col3
1.01 0.98 1.23

TO

final_col
1.01(0.98-1.23)

I am aware of the paste function with "sep" option to add characters between column, paste(col2, col3, sep ="-")

but I am stuck with adding the brackets and can it be done altogether.

Thanks for the suggestions

Upvotes: 0

Views: 172

Answers (2)

agstudy
agstudy

Reputation: 121608

Another option :

paste0(dx[,1],'(',paste0(dx[,-1],collapse='-'),')')
## [1] "1.01(0.98-1.23)"  

Upvotes: 1

akrun
akrun

Reputation: 887831

You can try

 do.call(sprintf, c(df1, fmt='%g(%g-%g)'))
 #[1] "1.01(0.98-1.23)" "0.2(1.3-1.2)" 

Or

 with(df1, paste0(col1,'(', col2, '-', col3, ')'))
 #[1] "1.01(0.98-1.23)" "0.2(1.3-1.2)"   

data

df1 <- data.frame(col1=c(1.01,0.2), col2=c(0.98, 1.3), 
                     col3=c(1.23, 1.2))

Upvotes: 1

Related Questions