Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read csv file in R

Tags:

r

csv

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.

like image 347
maggs Avatar asked Dec 24 '22 17:12

maggs


1 Answers

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)
like image 172
akrun Avatar answered Jan 05 '23 22:01

akrun