使用利用的函数read.table
:type.convert
。
例子:
df <- data.frame(a=c(" 1"," 2", " 3"), b=c("a","b","c"),
c=c(" 1.0", "NA", " 2.0"), d=c(" 1", "B", "2"))
str(df)
# 'data.frame': 3 obs. of 4 variables:
# $ a: Factor w/ 3 levels " 1"," 2"," 3": 1 2 3
# $ b: Factor w/ 3 levels "a","b","c": 1 2 3
# $ c: Factor w/ 3 levels " 1.0"," 2.0",..: 1 3 2
# $ d: Factor w/ 3 levels " 1","2","B": 1 3 2
df[] <- lapply(df, function(y) type.convert(as.character(y)))
df
# a b c d
# 1 1 a 1 1
# 2 2 b NA B
# 3 3 c 2 2
str(df)
# 'data.frame': 3 obs. of 4 variables:
# $ a: int 1 2 3
# $ b: Factor w/ 3 levels "a","b","c": 1 2 3
# $ c: num 1 NA 2
# $ d: Factor w/ 3 levels " 1","2","B": 1 3 2
(但我不确定这是否是你要找的......)
更新:如果你想创建一个colClasses
类型函数,也许你可以试试这样的函数。与您的问题标题不同,这不是“自动”的,但它确实允许您为每列指定列类,而不是让它自行type.convert
决定。
toColClasses <- function(inDF, colClasses) {
if (length(colClasses) != length(inDF)) stop("Please specify colClasses for each column")
inDF[] <- lapply(seq_along(colClasses), function(y) {
if (colClasses[y] == "") inDF[y] <- inDF[[y]]
else {
FUN <- match.fun(colClasses[y])
inDF[y] <- suppressWarnings(FUN(as.character(inDF[[y]])))
}
})
inDF
}
您可以按如下方式使用它:
df <- data.frame(a = c(" 1"," 2", " 3"), b = c("a","b","c"),
c = c(" 1.0", "NA", " 2.0"), d = c(" 1", "B", "2"))
df2 <- toColClasses(df, c("as.integer", "", "as.numeric", "as.character"))
df2
# a b c d
# 1 1 a 1 1
# 2 2 b NA B
# 3 3 c 2 2
str(df2)
# 'data.frame': 3 obs. of 4 variables:
# $ a: int 1 2 3
# $ b: Factor w/ 3 levels "a","b","c": 1 2 3
# $ c: num 1 NA 2
# $ d: chr " 1" "B" "2"
但是,您必须对该功能做更多的工作才能使其接受更广泛的as...
功能。