maggs
maggs

Reputation: 803

Read csv file in R

I am trying to read a .csv file in R. My file looks like this-

A,B,C,D,E

1,2,3,4,5

6,7,8,9,10

.

.

.

number of rows.

All are strings. First line is the header.

I am trying to read the file using-

mydata=read.csv("devices.csv",sep=",",header = TRUE)

But mydata is assigned X observations of 1 variable. Where X is number of rows. The whole row becomes a single column. But I want every header field in different column. I am not able to understand the problem.

Upvotes: 5

Views: 5764

Answers (2)

akrun
akrun

Reputation: 886928

If there are quotes ("), by using the code in the OP's post

str(read.csv("devices.csv",sep=",",header = TRUE))
#'data.frame':  2 obs. of  1 variable:
#$ A.B.C.D.E: Factor w/ 2 levels "1,2,3,4,5","6,7,8,9,10": 1 2

We could remove the " with gsub after reading the data with readLines and then use read.table

read.csv(text=gsub('"', '', readLines('devices.csv')), sep=",", header=TRUE)
#  A B C D  E
#1 1 2 3 4  5
#2 6 7 8 9 10

Another option if we are using linux would be to remove quotes with awk and pipe with read.csv

  read.csv(pipe("awk  'gsub(/\"/,\"\",$1)' devices.csv")) 
  #  A B C D  E
  #1 1 2 3 4  5
  #2 6 7 8 9 10

Or

 library(data.table)
 fread("awk  'gsub(/\"/,\"\",$1)' devices.csv") 
 #   A B C D  E
 #1: 1 2 3 4  5
 #2: 6 7 8 9 10

data

v1 <- c("A,B,C,D,E", "1,2,3,4,5", "6,7,8,9,10")
write.table(v1, file='devices.csv', row.names=FALSE, col.names=FALSE)

Upvotes: 10

Alekhya Vemavarapu
Alekhya Vemavarapu

Reputation: 1155

The code which you've written should work unless your csv file is corrupted.
Check giving absolute path of devices.csv

To test: data[1] will give you column 1 results

Or, You can try it this way too

data = read.table(text=gsub('"', '', readLines('//fullpath to devices.csv//')), sep=",", header=TRUE) 

Good Luck!

Upvotes: 1

Related Questions