Replacing square brackets with curly brackets in R

时间:2017-06-15 09:27:04

标签: r gsub

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.

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分:1)

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]"