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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With