有没有办法缩短一系列colClasses

时间:2014-05-29 15:28:34

标签: r

目前我正在阅读这样的数据文件:

setwd("N:/HH Scallop Growth Project/Ring data by cruise/")

growth <- read.csv("Growth.csv",sep=",",header=TRUE,
                    colClasses=c("character","character","character","numeric",
                                 "character","numeric","numeric","numeric",
                                 "numeric","numeric","numeric","numeric",
                                 "numeric","numeric","character","numeric",
                                 "character","numeric","numeric","numeric",
                                 "numeric","character","numeric","numeric",
                                 "numeric")) 

它工作正常,但它有点长/邋,有没有办法缩短/分组colClasses

3 个答案:

答案 0 :(得分:4)

rep函数怎么样:

R> rep(1:3, 2:4)
[1] 1 1 2 2 2 3 3 3 3

类似

cc = rep(c("character", "numeric"), c(2, 4))
read.csv("Growth.csv", header=TRUE, colClasses=cc)

答案 1 :(得分:4)

您可以构建一个包含长度和值的列表

xList <- list(lengths = c(3,1,1,9,1,1,1,4,1,3)
              , values = rep(c("character", "numeric"), 5))

然后使用inverse.rle

> inverse.rle(xList)
 [1] "character" "character" "character" "numeric"   "character" "numeric"   "numeric"   "numeric"  
 [9] "numeric"   "numeric"   "numeric"   "numeric"   "numeric"   "numeric"   "character" "numeric"  
[17] "character" "numeric"   "numeric"   "numeric"   "numeric"   "character" "numeric"   "numeric"  
[25] "numeric" 

答案 2 :(得分:4)

尝试创建一个25个向量,其条目全部为"numeric",然后只替换少数不在"character"的向量。另请注意,header=TRUEsep=","read.csv的默认值,因此可以省略它们。

colClasses <- replace(rep("numeric", 25), c(1:3, 5, 15, 17, 22), "character")
growth <- read.csv("Growth.csv", colClasses = colClasses)