How tp split snps name?
2
0
Entering edit mode
5.1 years ago
forever ▴ 80

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 • 1.4k views
ADD COMMENT
1
Entering edit mode

What have you tried?

ADD REPLY
0
Entering edit mode
5.1 years ago
zjhzwang ▴ 180

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"
ADD COMMENT
1
Entering edit mode

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

ADD REPLY
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

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"

ADD REPLY
0
Entering edit mode
5.1 years ago
forever ▴ 80

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

ADD COMMENT
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

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.

ADD REPLY
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

Yes, I will do. Thank you

ADD REPLY

Login before adding your answer.

Traffic: 2935 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6