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