有谁知道为什么参数colClasses
似乎不适用于read.xlsx
?
我创建了一个示例* .xlsx文件:
> library(xlsx)
> d1 = data.frame(A=LETTERS[1:3], B=letters[1:3], C=1:3, D=c(1.1, NA, NA))
> str(d1)
'data.frame': 3 obs. of 4 variables:
$ A: Factor w/ 3 levels "A","B","C": 1 2 3
$ B: Factor w/ 3 levels "a","b","c": 1 2 3
$ C: int 1 2 3
$ D: num 1.1 NA NA
> write.xlsx(d1, 'test.xlsx', sheetName='Sheet1', row.names=F, showNA=F)
然后尝试用read.xlsx
读取它,不带colClasses
参数:
> d2 = read.xlsx('test.xlsx', sheetName='Sheet1')
> str(d2)
'data.frame': 3 obs. of 4 variables:
$ A: Factor w/ 3 levels "A","B","C": 1 2 3
$ B: Factor w/ 3 levels "a","b","c": 1 2 3
$ C: num 1 2 3
$ D: num 1.1 NA NA
> d2 = read.xlsx('test.xlsx', sheetName='Sheet1', colClasses=c(B='character', 'A'='character'))
> str(d2)
'data.frame': 3 obs. of 4 variables:
$ A: Factor w/ 3 levels "A","B","C": 1 2 3
$ B: Factor w/ 3 levels "a","b","c": 1 2 3
$ C: num 1 2 3
$ D: num 1.1 NA NA
问题是colClasses
似乎没有效果。有什么想法吗?
感谢您的帮助。
阿列克谢
P.S。我有R 3.0.1,xlsx
0.5.1
答案 0 :(得分:12)
colClasses=
正在运行,但问题是当导入数据要将字符列转换为因子时,系统默认操作。
如果您导入test.xlsx
并将所有列设置为"character"
,则会看到所有列都是因素(也是数字)。
d2 = read.xlsx('test.xlsx', sheetName='Sheet1', colClasses=rep("character",4))
str(d2)
'data.frame': 3 obs. of 4 variables:
$ A: Factor w/ 3 levels "A","B","C": 1 2 3
$ B: Factor w/ 3 levels "a","b","c": 1 2 3
$ C: Factor w/ 3 levels "1","2","3": 1 2 3
$ D: Factor w/ 1 level "1.1": 1 NA NA
为确保不将字符转换为因子,您可以将参数stringsAsFactors=FALSE
添加到函数read.xlsx()
。
d2 = read.xlsx('test.xlsx', sheetName='Sheet1',
colClasses=c(B='character', A='character'),stringsAsFactors=FALSE)
str(d2)
'data.frame': 3 obs. of 4 variables:
$ A: chr "A" "B" "C"
$ B: chr "a" "b" "c"
$ C: num 1 2 3
$ D: num 1.1 NA NA