简体   繁体   English

将CSV文件导入到R-读取为字符的因子

[英]Importing csv file to R - factors read as characters

New to R. When importing a csv file columns are being read as characters when they are in fact - or should be - factors. R的新增功能。导入csv文件时,列实际上是-或者应该是-因素而被读取为字符。 All three columns in question have only two levels (yes/no and male/female). 有问题的所有三列都只有两个级别(是/否和男性/女性)。

My attempt: In the Import Text Data dialog box I change the the columns to factor by inserting a comma separated list of factors. 我的尝试:在“导入文本数据”对话框中,通过插入以逗号分隔的因子列表,将列更改为因子。

> LungCapDataCSVnew <- read_csv("~/file.csv", 
  col_types = cols(Caesarean = col_factor(levels = c("no", 
  "yes")), Gender = col_factor(levels = c("male", 
  "female")), Smoke = col_factor(levels = c("no", 
  "yes"))))

> View(file)

> class(Gender)
[1] "character"

> class(Smoke)
[1] "character"

As it shows, 'Gender' and 'Smoke' columns read as characters when they should be factors. 如图所示,“性别”和“烟熏”列在应作为要素时读作字符。

How to solve this? 如何解决呢?

It's strange that simply read.csv() without any extra arguments doesn't automatically read in your characters as factors. 奇怪的是,没有任何额外参数的read.csv()不会自动将您的字符作为要素读取。

After importing the file with file <- read.csv("~/file.csv") you can try 使用file <- read.csv("~/file.csv")导入文件后,您可以尝试

i <- sapply(file, is.character)
file[i] <- lapply(file[i], as.factor)

To convert all character columns into factors 将所有字符列转换为因子

Use can change character into factor 使用可以将性格变成因素

LungCapDataCSVnew$Smoke<-as.factor(LungCapDataCSVnew$Smoke)
LungCapDataCSVnew$Gender<-as.factor(LungCapDataCSVnew$Gender)

New to R . R的新手。 Suggesting website- http://cran.r-project.org/manuals.html 建议网站-http : //cran.r-project.org/manuals.html

Thanks 谢谢

正如我刚刚发现的那样:read.csv似乎可以检测到因素和级别read_csv不会,它只是将列标题分配为字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM