Imported a csv-dataset to R but the values becomes factors

后端 未结 8 1448
灰色年华
灰色年华 2020-11-29 01:19

I am very new to R and I am having trouble accessing a dataset I\'ve imported. I\'m using RStudio and used the Import Dataset function when importing my csv-file and pasted

8条回答
  •  醉酒成梦
    2020-11-29 01:52

    None of these answers mention the colClasses argument which is another way to specify the variable classes in read.csv.

     stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = "numeric") # all variables to numeric
    

    or you can specify which columns to convert:

    stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = c("PTS" = "numeric", "MP" = "numeric") # specific columns to numeric
    

    Note that if a variable can't be converted to numeric then it will be converted to factor as default which makes it more difficult to convert to number. Therefore, it can be advisable just to read all variables in as 'character' colClasses = "character" and then convert the specific columns to numeric once the csv is read in:

    stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = "character")
    point <- as.numeric(stuckey$PTS)
    time <- as.numeric(stuckey$MP)
    

提交回复
热议问题