4

R 通常以“错误”格式理解数据框列,或者您只需将列类从因子更改为字符即可对其进行修改。我以前一直在以下列方式更改列类:

set.seed(1)

df <- data.frame(x = 1:10,
y = rep(1:2, 5),
k = rnorm(10, 5,2),
z = rep(c(2010, 2012, 2011, 2010, 1999), 2),
j = c(rep(c("a", "b", "c"), 3), "d"))

x <- c("y", "z")

for(i in 1:length(x)){
df[,x[i]] <- factor(df[,x[i]])}

回到数字:

x <- 1:5

for(i in 1:length(x)){
df[,x[i]] <- as.numeric(as.character(df[,x[i]]))} # Character cannot become numeric

我突然想到,也许有更好的方法来做到这一点。我发现了这个问题,这几乎正是我所需要的:

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

但是,对于此函数,必须为每一列指定向量类型:

convert.magic(df, rep("factor",5))

convert.magic(df, c("character", "factor"))
# Error in FUN(1:5[[1L]], ...) : could not find function "FUN1"

有人可以帮我重建这个函数,让它与列名和数字一起工作吗?恐怕这对我来说太先进了……

x <- c("y", "z")
convert.magic(df, "character", x)
4

1 回答 1

6
df <- data.frame(x = 1:10,
                 y = rep(1:2, 5),
                 k = rnorm(10, 5,2),
                 z = rep(c(2010, 2012, 2011, 2010, 1999), 2),
                 j = c(rep(c("a", "b", "c"), 3), "d"))

convert.magic <- function(obj, type){
  FUN1 <- switch(type,
                 character = as.character,
                 numeric = as.numeric,
                 factor = as.factor)
  out <- lapply(obj, FUN1)
  as.data.frame(out)
}

str(df)
str(convert.magic(df, "character"))
str(convert.magic(df, "factor"))
df[, c("x", "y")] <- convert.magic(df[, c("x", "y")], "factor")
于 2012-06-29T14:13:40.130 回答