supply a vector to “classes” of dataframe

后端 未结 2 761
太阳男子
太阳男子 2021-01-04 09:23

You know how you can supply a vector of names to a data frame to change the col or row names of a dataframe. Is there a similar method to supply a vector of names that alte

2条回答
  •  情深已故
    2021-01-04 09:52

    It seems class(x) <- "factor" doesn't work and neither does as(x, "factor"), so I don't know of a direct way of doing what you want.

    ...But a slightly more explicit way is:

    # Coerces data.frame columns to the specified classes
    colClasses <- function(d, colClasses) {
        colClasses <- rep(colClasses, len=length(d))
        d[] <- lapply(seq_along(d), function(i) switch(colClasses[i], 
            numeric=as.numeric(d[[i]]), 
            character=as.character(d[[i]]), 
            Date=as.Date(d[[i]], origin='1970-01-01'), 
            POSIXct=as.POSIXct(d[[i]], origin='1970-01-01'), 
            factor=as.factor(d[[i]]),
            as(d[[i]], colClasses[i]) ))
        d
    }
    
    # Example usage
    DF <- as.data.frame(matrix(rnorm(25), 5, 5))
    DF2 <- colClasses(DF, c(rep("character", 3), rep("factor", 2)))
    str(DF2)
    
    DF3 <- colClasses(DF, 'Date')
    str(DF3)
    

    A couple of things: you can add more cases as needed. And the first line of the function allows you to call with a single class name. The last "default" case of the switch calls the as function and you mileage might vary.

提交回复
热议问题