Similar to your solution but taking advantage of vectorization (of strsplit): cbind(test[,1], do.call(rbind, strsplit(test[,1], ":")))
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
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"
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
Log in to answer this question.
What have you tried?