首页 > 解决方案 > 将字符串作为因素读取的问题;前面的空格似乎很重要

问题描述

在具有因素的 textConnection() 迷你文件中读取时出现问题。下面的这个片段为“LabAuto”提供了两个独立的因素。

x <- read.table(tc <- textConnection(
"Project, TestingType, CodeType
'TS',     'TDDEUT',    Production
'TS',     'TDDEUT',    Testing
'NR',      'LabAuto',  Production
'In',     'LabAuto',   Testing"),
    header=TRUE, colClasses=c("character", "factor", "factor"),
    sep=",", na.strings=c("NULL"), quote="'")

TestingType 显示了这一点,表明有两个级别标记为(大约)LabAuto:

> x$TestingType
[1]      TDDEUT        TDDEUT         LabAuto      LabAuto 
Levels:       LabAuto      LabAuto      TDDEUT

表面上这是由于第一个“LabAuto”因子前面的额外空间,因为如果我删除一个空格(在“NR”行上),那么我最终会得到 TestingType 的两个因子,正如我想要的那样:

> x$TestingType
[1]      TDDEUT       TDDEUT       LabAuto      LabAuto
Levels:      LabAuto      TDDEUT

但是不应该指定 sep="," 和 quote="'" 参数告诉 R 只考虑单引号内的文本作为因子标签?

单引号不是唯一的问题,因为上面的第三列有同样的问题:

> x$CodeType
[1]     Production     Testing      Production      Testing    
Levels:     Production     Testing    Testing   Production

它显示了 4 个不同的因素而不是 2 个,表面上也是因为每个因素前面有不同数量的空格。在从文本输入文件中制作因子级别时,有没有办法告诉 R 忽略空格?谢谢。

标签: r

解决方案


您的输入文件的格式非常奇怪。通常,您要么有分隔符,要么有分隔值的空格。你似乎两者都有,这很奇怪。但是如果你使用strip.white=参数 to ,你可以去掉空格read.table。利用

x <- read.table(tc <- textConnection(
  "Project, TestingType, CodeType
'TS',     'TDDEUT',    Production
'TS',     'TDDEUT',    Testing
'NR',      'LabAuto',  Production
'In',     'LabAuto',   Testing"),
  header=TRUE, colClasses=c("character", "factor", "factor"),
  sep=",", na.strings=c("NULL"), quote="'", strip.white = TRUE)

x$TestingType
# [1] TDDEUT  TDDEUT  LabAuto LabAuto
# Levels: LabAuto TDDEUT

推荐阅读