This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How tp split snps name?

Hi everyone, I have the below file:

chr1:109457160 2 C C 0.8609 [T/G]

chr1:109457233 2 C C 0.7725 [T/G]

chr1:109457614 2 - - 0.0000 [T/C]

I need to get new one like:

chr1:109457160 chr1 109457160

chr1:109457233 chr1 109457233

chr1:109457614 chr1 109457614

How to do it in R?

I appreciate your reply

snp r

2 answers

Have you tried strsplit{base}?This function can split strings.

 test<-matrix(
  c(
    "chr1:109457160","2","C","C","0.8609","[T/G]",
    "chr1:109457233","2","C","C","0.7725","[T/G]",
    "chr1:109457614","2","-","-","0.0000","[T/C]"
  ),
  nrow = 3,
  byrow=T
)
split_func<-function(x){
  return(c(x[1],strsplit(x[1],":")[[1]]))
}
result<-t(apply(test,1,split_func))

And the result is:

> result
     [,1]             [,2]   [,3]       
[1,] "chr1:109457160" "chr1" "109457160"
[2,] "chr1:109457233" "chr1" "109457233"
[3,] "chr1:109457614" "chr1" "109457614"

Similar to your solution but taking advantage of vectorization (of strsplit): cbind(test[,1], do.call(rbind, strsplit(test[,1], ":")))

Yeah,you are right.But I think apply families are more suitable for most situation.

It is a long list in txt file. I can not create matrix c myself. if my data saved in txt file like a.txt

a=read.table("a.txt") split_func<-function(x){ return(a(x[1],strsplit(x[1],":")[[1]])) } result<-t(apply(a,1,split_func))

so I get the below error:

Error in FUN(newX[, i], ...) : could not find function "a"

When I try strsplit(a[1],":") I got Error in strsplit(a[1], ":") : non-character argument

You may have a factor. Try coercing the data to character with as.character.

r<-strsplit(as.character(a[1,1]),":") "chr1" "109457160" now how can I access only chr1 I try r[1,1] but it does not work.

strsplit return a list,so you need to call r[[1]][1].

Please use ADD COMMENT or ADD REPLY to answer to earlier posts, as such this thread remains logically structured and easy to follow.

Yes, I will do. Thank you

Log in to answer this question.