Reputation: 121
Im trying to take in a table from a text file and then output it (or convert it) to a csv for easier manipulation. I looked and cannot find any specific help on this task.
The text file looks something like this:
C# CLA OLA Quiz Exam FinalExam
c1234501 10 20 10 30 30
c1234502 9 10 5 20 20
c1234503 10 17 8 27 27
c1234504 8 14 10 29 15
c1234505 7 18 3 24 27
and I would like to get it to output like this:
C#,CLA,OLA,Quiz,Exam,FinalExam,
c1234501,10,20,10,30,30,
c1234502,9,10,5,20,20,
c1234503,10,17,8,27,27,
c1234504,8, 14, 10, 29, 15,
c1234505,7, 18, 3, 24, 27,
with the comma as the delimiter. So far Ive come up with this code:
tab = read.delim(file, header = TRUE)
write.table(tab, file="name_file.csv",sep=",",col.names=TRUE,row.names=FALSE)
but the results arent what I thought they would be:
"C.","CLA.OLA.Quiz.Exam.FinalExam"
"c1234501","10 20 10 30 30"
"c1234502"," 9 10 5 20 20"
"c1234503","10 17 8 27 27"
"c1234504 "," 8 14 10 29 15"
"c1234505 "," 7 18 3 24 27"
any help would be greatly appreciated. Thanks!
Upvotes: 0
Views: 3028
Reputation: 8856
In explicit terms:
tab <- read.table("name_file.txt", comment="", header=TRUE)
write.csv(tab, "name_file.csv", row.names=FALSE, quote=FALSE)
I know you didn't ask for it, but if you're essentially using R as a file converter, it might be more convenient to just use sed
or something similar through a console/terminal. F.ex:
sed -E 's/[[:blank:]]+/,/g' name_file.txt > name_file.csv
Upvotes: 2