[R] how do I separete coloumns by comma?

arun smartpink111 at yahoo.com
Fri Dec 13 18:10:33 CET 2013


Hi,
Try:
mydata <- read.table("data.txt") #or read.table("data.txt",sep="")
 str(mydata)
#'data.frame':    6 obs. of  6 variables:
# $ V1: int  1 1 1 1 1 1
# $ V2: int  4 4 4 2 2 2
# $ V3: int  4 2 5 3 3 3
# $ V4: int  1 2 1 1 1 1
# $ V5: int  6 3 2 1 2 4
# $ V6: int  23 28 24 24 40 22


 write.table(mydata,"dataNew.txt",sep=",",row.names=FALSE,quote=FALSE)
##dataNew.txt
V1,V2,V3,V4,V5,V6
1,4,4,1,6,23
1,4,2,2,3,28
1,4,5,1,2,24
1,2,3,1,1,24
1,2,3,1,2,40
1,2,3,1,4,22
#or

 Lines1 <- readLines("data.txt")
 gsub(" +",",",Lines1)
#[1] "1,4,4,1,6,23" "1,4,2,2,3,28" "1,4,5,1,2,24" "1,2,3,1,1,24" "1,2,3,1,2,40"
#[6] "1,2,3,1,4,22"

A.K.




Hi every one, 


I have a text file like this: 
1    4   4    1    6    23 
1   4    2    2    3    28 
1    4    5    1    2    24 
1    2    3    1    1    24 
1   2    3    1    2     40 
1   2   3    1    4      22 

I want to separate columns by comma, like this: 
1,4,4,1,6,23 
1,4,2,2,3,28 
1,4,5,1,2,24 
1,2,3,1,1,24 
1,2,3,1,2,40 
1,2,3,1,4,22   

I used this code: 
mydata=read.table("data.txt",sep=",") 
but I see this output: 
1\t4\t4\t1\t6\t231\t4\t2\t2\t3\t28 
...  
please correct my code 
Thanks in advance 
Elham



More information about the R-help mailing list