Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a one lined CSV in R?

Tags:

r

csv

I have been working on a dummy dataset recently and i found out that the data provided to me was all in single line. A similiar example for the same is depicted as follows:

Name,Age,Gender,Occupation A,10,M,Student B,11,M,Student C,11,F,Student

i want to import the data and obtain an output as follows:

Name  Age  Gender  Occupation
 A    10     M       Student
 B    11     M       Student
 C    12     F       Student

a case may arise that a value might be missing. a logic is required to import such data. Can anyone help me out to build a logic behind the import of such data sets.

i tried the normal import but it really didn't helped. just imported the file by read.csv() function and it didn't gave me an expected result.

EDIT: what if the data is like:

Name,Age,Gender,Occupation ABC XYZ,10,M,Student B,11,M,Student C,11,F,Student

and i want an output like:

  Name     Age  Gender  Occupation
 ABC XYZ    10     M       Student
   B        11     M       Student
   C        12     F       Student
like image 201
desmond.carros Avatar asked Nov 30 '22 23:11

desmond.carros


1 Answers

You could read your file in with readLines, turn spaces into line breaks, and then read it with read.csv:

# txt <- readLines("my_data.txt") # with a real data file
txt <- readLines(textConnection("Name,Age,Gender,Occupation A,10,M,Student B,11,M,Student C,11,F,Student"))

read.csv(text=gsub(" ","\n",txt))

output

  Name Age Gender Occupation
1    A  10      M    Student
2    B  11      M    Student
3    C  11      F    Student
like image 78
scoa Avatar answered Dec 05 '22 12:12

scoa