r - 将字符串作为因素读取的问题;前面的空格似乎很重要
问题描述
在具有因素的 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 忽略空格?谢谢。
解决方案
您的输入文件的格式非常奇怪。通常,您要么有分隔符,要么有分隔值的空格。你似乎两者都有,这很奇怪。但是如果你使用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
推荐阅读
- python - 制作新网址/查看 Django 时找不到页面
- javascript - 返回下拉选择的选项的功能反应
- scrapy - scrapy.Request 无法下载页面
- arrays - 在数据库中注册的照片在我的系统中重复列出时
- pandas - 如何从数据框中映射值并获取最后更新
- java - Python 用 Crypto 解密:前 16 个字符是乱码
- swift - 如何使用 UIKit 复制连接 iOS 14 iMessage 回复的曲线?
- javascript - 文档不适用于模板文字
- swift - 如何使 TextField 退出其编辑模式
- flutter - 我想在用户不活动后切换屏幕