Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am using R and want to covert following:

"A,B"

to

"A","B" OR 'A','B'

I tried str_replace(), but that's not working out.

Please suggest, thanks.


Update

I tried the suggested answer by d.b. Though it works, but I didn't realize that I should have shared that, I am going to use above solution for vector. I need the values in data with "A,B" to split in order to use it as a vector.

Using strsplit

> data
[1] "A,B"
> test <- strsplit(x = data, split = ",")
> test
[[1]]
[1] "A" "B"

above test won't be useful because I can't use it for following:

> output_1 <- c(test)
> outputFinalData <- outputFinal[outputFinal$Column %in% output_1,]

outputFinalData is empty with above process. But is not empty when I do:

> output_2 <- c("A", "B") 
> outputFinalData <- outputFinal[outputFinal$Column %in% output_2,]

Also, output_1 and output_2 are not same:

> output_1
[[1]]
[1] "Bin_14" "Bin_15"
> output_2
[1] "Bin_14" "Bin_15"
> output_1 == output_2
[1] FALSE FALSE
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
159 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use strsplit:

> data = "A,B"
> strsplit(x=data,split=",")
[[1]]
[1] "A" "B"

Note that it returns a list with a vector. The list is length one because you asked it to split one string. If you ask it to split two strings you get a list of length 2:

> data = c("A,B","Foo,bar")
> strsplit(x=data,split=",")
[[1]]
[1] "A" "B"

[[2]]
[1] "Foo" "bar"

So if you know you are only going to have one thing to split you can get a vector of the parts by taking the first element:

> data = "A,B"
> strsplit(x=data,split=",")[[1]]
[1] "A" "B"

However it might be more efficient to do a load of splits in one go and put the bits in a matrix. As long as you can be sure everything splits into the same number of parts, then something like:

> data = c("A,B","Foo,bar","p1,p2")
> do.call(rbind,(strsplit(x=data,split=",")))
     [,1]  [,2] 
[1,] "A"   "B"  
[2,] "Foo" "bar"
[3,] "p1"  "p2" 
> 

Gets you the two parts in columns of a matrix that you can then add to a data frame if that's what you need.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...