Read a CSV in R, from another one generated by R

2

I explain my current situation, I want to be able to save a CSV file in one operating system and load it in the other without having to indicate the type of column. I explain why. When you have in R a data.frame style:

data.frame(V1=c("1","2","3"),V2=c(1,2,3), stringAsFactor=TRUE)

When you write a CSV with this data.frame it would look like this:

"V1","V2"
"1", 1
"2", 2
"3", 3

On the other hand, when the CSV is read, the V1 column is equal to V2 . Is there a function that detects the quotes and encodes it as factor ?

Thank you very much in advance.

    
asked by APT22 03.09.2018 в 17:11
source

1 answer

0

In principle, the same function can serve you, with the exception that you must indicate the type of data. Let's see:

df <- data.frame(V1=c("1","2","3"),
                 V2=c(1,2,3),
                 stringsAsFactors = T,
                 row.names=NULL
                 )
str(df)
'data.frame':   3 obs. of  2 variables:
 $ V1: Factor w/ 3 levels "1","2","3": 1 2 3
 $ V2: num  1 2 3

Now, we should read the saved file, but indicating the nature of each column using the colClasses parameter:

df <- read.csv("Ejemplo.csv", 
               colClasses=c("factor", "numeric"))

str(df)
'data.frame':   3 obs. of  2 variables:
 $ V1: Factor w/ 3 levels "1","2","3": 1 2 3
 $ V2: num  1 2 3

Another more automatic way and maybe closer to what you are looking for, would be to ignore the " , let the strings happen as they are in the file, that is to say, this will assure us that the numbers will follow being considered chains, the problem that has this, is that the levels of the factor will have quotes, so the only thing that would remain is to remove them, something like this:

df <- read.csv("Ejemplo.csv", 
               quote = "",
               stringsAsFactors = T)

for (f in names(df)[sapply(df, is.factor)]) {
    levels(df[,f]) <- gsub("\"", "", levels(df[,f]))
}
str(df)
'data.frame':   3 obs. of  2 variables:
 $ X.V1.: Factor w/ 3 levels "1","2","3": 1 2 3
 $ X.V2.: int  1 2 3
    
answered by 04.09.2018 / 02:07
source