一次转换数据框的多个列的类型

我似乎花了很多时间从文件,数据库或其他东西创建一个数据框,然后将每一列转换成我想要的类型(数字,因子,字符等)。有没有一种方法可以一步一步做到这一点,可能是通过提供类型向量来实现的?


foo<-data.frame(x=c(1:10), 

                y=c("red", "red", "red", "blue", "blue", 

                    "blue", "yellow", "yellow", "yellow", 

                    "green"),

                z=Sys.Date()+c(1:10))


foo$x<-as.character(foo$x)

foo$y<-as.character(foo$y)

foo$z<-as.numeric(foo$z)

而不是最后三个命令,我想做类似的事情


foo<-convert.magic(foo, c(character, character, numeric))


月关宝盒
浏览 768回答 3
3回答

慕哥6287543

我对Brandon的回答的评论switch如下:convert.magic <- function(obj,types){&nbsp; &nbsp; for (i in 1:length(obj)){&nbsp; &nbsp; &nbsp; &nbsp; FUN <- switch(types[i],character = as.character,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;numeric = as.numeric,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;factor = as.factor)&nbsp; &nbsp; &nbsp; &nbsp; obj[,i] <- FUN(obj[,i])&nbsp; &nbsp; }&nbsp; &nbsp; obj}out <- convert.magic(foo,c('character','character','numeric'))> str(out)'data.frame':&nbsp; &nbsp;10 obs. of&nbsp; 3 variables:&nbsp;$ x: chr&nbsp; "1" "2" "3" "4" ...&nbsp;$ y: chr&nbsp; "red" "red" "red" "blue" ...&nbsp;$ z: num&nbsp; 15254 15255 15256 15257 15258 ...对于真正的大数据帧,您可能要使用lapply而不是for循环:convert.magic1 <- function(obj,types){&nbsp; &nbsp; out <- lapply(1:length(obj),FUN = function(i){FUN1 <- switch(types[i],character = as.character,numeric = as.numeric,factor = as.factor); FUN1(obj[,i])})&nbsp; &nbsp; names(out) <- colnames(obj)&nbsp; &nbsp; as.data.frame(out,stringsAsFactors = FALSE)}执行此操作时,请注意R中强制数据的一些复杂性。例如,从因数转换为数值通常涉及as.numeric(as.character(...))。此外,要注意data.frame()和as.data.frame()S转换性格因素的默认行为。

人到中年有点甜

我知道我回答的时间很晚,但是将循环和属性函数一起使用是解决问题的简单方法。names <- c("x", "y", "z")chclass <- c("character", "character", "numeric")for (i in (1:length(names))) {&nbsp; attributes(foo[, names[i]])$class <- chclass[i]}
打开App,查看更多内容
随时随地看视频慕课网APP