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

时间:2011-10-06 21:56:40

标签: r type-conversion

我似乎花了很多时间从文件,数据库或其他东西创建数据框,然后将每列转换为我想要的类型(数字,因子,字符等)。有没有办法一步完成,可能是通过给出一个类型的向量?

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))

11 个答案:

答案 0 :(得分:32)

修改有关此基本构思的一些简化和扩展,请参阅this相关问题。

我使用switch评论Brandon的回答:

convert.magic <- function(obj,types){
    for (i in 1:length(obj)){
        FUN <- switch(types[i],character = as.character, 
                                   numeric = as.numeric, 
                                   factor = as.factor)
        obj[,i] <- FUN(obj[,i])
    }
    obj
}

out <- convert.magic(foo,c('character','character','numeric'))
> str(out)
'data.frame':   10 obs. of  3 variables:
 $ x: chr  "1" "2" "3" "4" ...
 $ y: chr  "red" "red" "red" "blue" ...
 $ z: num  15254 15255 15256 15257 15258 ...

对于真正大型的数据框,您可能希望使用lapply代替for循环:

convert.magic1 <- function(obj,types){
    out <- lapply(1:length(obj),FUN = function(i){FUN1 <- switch(types[i],character = as.character,numeric = as.numeric,factor = as.factor); FUN1(obj[,i])})
    names(out) <- colnames(obj)
    as.data.frame(out,stringsAsFactors = FALSE)
}

执行此操作时,请注意在R中强制数据的某些复杂性。例如,从因子转换为数字通常涉及as.numeric(as.character(...))。另请注意data.frame()as.data.frame()将字符转换为因子的默认行为。

答案 1 :(得分:17)

如果您想自动检测列数据类型而不是手动指定它(例如,在数据整理等之后),函数type.convert()可能会有所帮助。

函数type.convert()接受一个字符向量,并尝试确定所有元素的最佳类型(意味着每列必须应用一次)。

df[] <- lapply(df, function(x) type.convert(as.character(x)))

因为我喜欢dplyr,所以我更喜欢:

library(dplyr)
df <- df %>% mutate_all(funs(type.convert(as.character(.))))

答案 2 :(得分:7)

我发现我也经常遇到这种情况。这是关于如何导入数据的。所有read ...()函数都有某种类型的选项来指定不将字符串转换为因子。这意味着文本字符串将保留字符,而看起来像数字的内容将保留为数字。如果元素为空且不是NA,则会出现问题。但同样,na.strings = c(“”,......)也应解决这个问题。我首先要仔细研究你的导入过程并相应地进行调整。

但是你总是可以创建一个函数并推送这个字符串。

convert.magic <- function(x, y=NA) {
for(i in 1:length(y)) { 
if (y[i] == "numeric") { 
x[i] <- as.numeric(x[[i]])
}
if (y[i] == "character")
x[i] <- as.character(x[[i]])
}
return(x)
}

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

> str(foo)
'data.frame':   10 obs. of  3 variables:
 $ x: chr  "1" "2" "3" "4" ...
 $ y: chr  "red" "red" "red" "blue" ...
 $ z: num  15254 15255 15256 15257 15258 ...

答案 3 :(得分:5)

我知道我回答很晚,但是使用循环和属性函数是解决问题的简单方法。

names <- c("x", "y", "z")
chclass <- c("character", "character", "numeric")

for (i in (1:length(names))) {
  attributes(foo[, names[i]])$class <- chclass[i]
}

答案 4 :(得分:2)

我刚刚使用RSQLite fetch方法遇到了类似的事情......结果以原子数据类型的形式返回。在我的情况下,这是一个日期时间戳,让我感到沮丧。 我发现setAs函数对于帮助as按预期工作非常有用。这是我的小例子。

##data.frame conversion function
convert.magic2 <- function(df,classes){
  out <- lapply(1:length(classes),
                FUN = function(classIndex){as(df[,classIndex],classes[classIndex])})
  names(out) <- colnames(df)
  return(data.frame(out))
}

##small example case
tmp.df <- data.frame('dt'=c("2013-09-02 09:35:06", "2013-09-02 09:38:24", "2013-09-02 09:38:42", "2013-09-02 09:38:42"),
                     'v'=c('1','2','3','4'),
                     stringsAsFactors=FALSE)
classes=c('POSIXct','numeric')
str(tmp.df)
#confirm that it has character datatype columns
##  'data.frame':  4 obs. of  2 variables:
##    $ dt: chr  "2013-09-02 09:35:06" "2013-09-02 09:38:24" "2013-09-02 09:38:42" "2013-09-02 09:38:42"
##    $ v : chr  "1" "2" "3" "4"

##is the dt column coerceable to POSIXct?
canCoerce(tmp.df$dt,"POSIXct")
##  [1] FALSE

##and the conver.magic2 function fails also:
tmp.df.n <- convert.magic2(tmp.df,classes)

##  Error in as(df[, classIndex], classes[classIndex]) : 
##    no method or default for coercing “character” to “POSIXct” 

##ittle reading reveals the setAS function
setAs('character', 'POSIXct', function(from){return(as.POSIXct(from))})

##better answer for canCoerce
canCoerce(tmp.df$dt,"POSIXct")
##  [1] TRUE

##better answer from conver.magic2
tmp.df.n <- convert.magic2(tmp.df,classes)

##column datatypes converted as I would like them!
str(tmp.df.n)

##  'data.frame':  4 obs. of  2 variables:
##    $ dt: POSIXct, format: "2013-09-02 09:35:06" "2013-09-02 09:38:24" "2013-09-02 09:38:42" "2013-09-02 09:38:42"
##   $ v : num  1 2 3 4

答案 5 :(得分:1)

一个简单的data.table解决方案,但如果要更改为许多不同的列类型,则需要几个步骤。

$scope.timeDisplay[0];

这会将除dt <- data.table( x=c(1:10), y=c(10:20), z=c(10:20), name=letters[1:10]) dt <- dt[, lapply(.SD, as.numeric), by= name] 中指定的列以外的所有列更改为数字(或您在by中设置的任何内容)

答案 6 :(得分:1)

类似于type.convert(foo, as.is = TRUE),还有readr::type_convert可以将数据帧转换为适当的类,而无需指定它们

readr::type_convert(foo) 

如果将所有列都保留为字符,我们也可以使用readr::parse_guess,它将自动将数据框转换为正确的类。考虑修改后的数据框

foo <- data.frame(x = as.character(1:10), 
                  y = c("red", "red", "red", "blue", "blue", "blue", "yellow", 
                     "yellow", "yellow", "green"),
                  z = as.character(Sys.Date()+c(1:10)), stringsAsFactors = FALSE)

str(foo)

#'data.frame':  10 obs. of  3 variables:
# $ x: chr  "1" "2" "3" "4" ...
# $ y: chr  "red" "red" "red" "blue" ...
# $ z: chr  "2019-08-12" "2019-08-13" "2019-08-14" "2019-08-15" ...

在每列上应用parse_guess

foo[] <- lapply(foo, readr::parse_guess)

#'data.frame':  10 obs. of  3 variables:
# $ x: num  1 2 3 4 5 6 7 8 9 10
# $ y: chr  "red" "red" "red" "blue" ...
# $ z: Date, format: "2019-08-12" "2019-08-13" "2019-08-14" "2019-08-15" ...

答案 7 :(得分:1)

hablar软件包中有一个简单的解决方案

代码

library(hablar)
library(dplyr)
df <- data.frame(x = "1", y = "2", z = "4")

df %>% 
  convert(int(x, z),
          chr(y))

结果

# A tibble: 1 x 3
      x y         z
  <int> <chr> <int>
1     1 2         4

您可以简单地输入多个列名来转换多个列,例如将zz转换为整数,如上例所示。

答案 8 :(得分:0)

除了@joran的答案之外,其中convert.magic不会在因子到数字转换中保留数值:

convert.magic <- function(obj,types){
    out <- lapply(1:length(obj),FUN = function(i){FUN1 <- switch(types[i],
    character = as.character,numeric = as.numeric,factor = as.factor); FUN1(obj[,i])})
    names(out) <- colnames(obj)
    as.data.frame(out,stringsAsFactors = FALSE)
}

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)

str(foo)
# 'data.frame': 10 obs. of  3 variables:
# $ x: chr  "1" "2" "3" "4" ...
# $ y: chr  "red" "red" "red" "blue" ...
# $ z: num  16777 16778 16779 16780 16781 ...

foo.factors <- convert.magic(foo, rep("factor", 3))

str(foo.factors) # all factors

foo.numeric.not.preserved <- convert.magic(foo.factors, c("numeric", "character", "numeric"))

str(foo.numeric.not.preserved)
# 'data.frame': 10 obs. of  3 variables:
# $ x: num  1 3 4 5 6 7 8 9 10 2
# $ y: chr  "red" "red" "red" "blue" ...
# $ z: num  1 2 3 4 5 6 7 8 9 10

# z comes out as 1 2 3...

以下应保留数值:

## as.numeric function that preserves numeric values when converting factor to numeric

as.numeric.mod <- function(x) {
    if(is.factor(x))
      as.numeric(levels(x))[x]
  else
      as.numeric(x)
}

## The same than in @joran's answer, except for as.numeric.mod
convert.magic <- function(obj,types){
    out <- lapply(1:length(obj),FUN = function(i){FUN1 <- switch(types[i],
    character = as.character,numeric = as.numeric.mod, factor = as.factor); FUN1(obj[,i])})
    names(out) <- colnames(obj)
    as.data.frame(out,stringsAsFactors = FALSE)
}

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

str(foo.numeric)
# 'data.frame': 10 obs. of  3 variables:
# $ x: num  1 2 3 4 5 6 7 8 9 10
# $ y: chr  "red" "red" "red" "blue" ...
# $ z: num  16777 16778 16779 16780 16781 ...

# z comes out with the correct numeric values

答案 9 :(得分:0)

变换就像你似乎描述的那样:

document.addEventListener("DOMContentLoaded", function(){
    //document.write("<style>body {opacity 0;}</style>");
    //var style = document.createElement('style');
    //style.type = 'text/css';
    //style.innerHTML = 'body {opacity 0;}';
    //document.getElementsByTagName('head')[0].appendChild(style);
    document.body.style.opacity = 0;
    document.body.style.transition = 'none';
    window.onload=function(){
        document.body.style.opacity = 1;
        document.body.style.transition = '500ms opacity';
    };
});

function enableRotator(){
    //plugin goes here....
}

答案 10 :(得分:0)

使用purrrbase

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))
types <- c("character", "character", "numeric")
types<-paste0("as.",types)
purrr::map2_df(foo,types,function(x,y) do.call(y,list(x)))
# A tibble: 10 x 3
   x     y          z
   <chr> <chr>  <dbl>
 1 1     red    18127
 2 2     red    18128
 3 3     red    18129
 4 4     blue   18130