Can anybody tell me how to replace square brackets with curly brackets in R. For example [1,2,3]
to {1,2,3}
. I know it could be done with "gsub" function but do not know how.
Asked
Active
Viewed 4,374 times
2

Huy Nguyen Bui
- 326
- 1
- 3
- 9
-
2https://stackoverflow.com/questions/33608060/how-to-replace-square-brackets-with-curly-brackets-using-rs-regex – AK88 Jun 15 '17 at 09:28
2 Answers
4
We can use gsub
to remove the []
and then paste
the {}
paste0("{", gsub("[][]", "", str1), "}")
#[1] "{1,2,3}"
Or another option is chartr
chartr("[]", "{}", str1)
#[1] "{1,2,3}"
data
str1 <- "[1,2,3]"

akrun
- 874,273
- 37
- 540
- 662
2
Here you have a possible option using gsub
twice:
gsub("\\]", "}", gsub("\\[", "{", "[1, 2, 3]"))
It first replaces ]
for }
and then [
for {
to the resulting string.

Carles Mitjans
- 4,786
- 3
- 19
- 38