Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中的函数中存储列号_R - Fatal编程技术网

在R中的函数中存储列号

在R中的函数中存储列号,r,R,我试图将列数存储到x的变量中, y和z,以便我以后可以更改它们的类。变量看起来是这样的:x=c2,3,4,5,6,7,8 相反,当我运行时,我会收到以下消息: FUNX[[i]]中出现错误,…:无效的“长度”参数 NAcorrected.data就是我想要应用column类中的更改的数据集 干杯 clean.data <- function(x, y, z) { factors <- x integers <- y numerics <- z

我试图将列数存储到x的变量中, y和z,以便我以后可以更改它们的类。变量看起来是这样的:x=c2,3,4,5,6,7,8

相反,当我运行时,我会收到以下消息:

FUNX[[i]]中出现错误,…:无效的“长度”参数

NAcorrected.data就是我想要应用column类中的更改的数据集

干杯

clean.data <- function(x, y, z) {
    factors <- x
    integers <- y
    numerics <- z

    cleaned.data <- NAcorrected.data
    cleaned.data[factors] <- lapply(cleaned.data[factors], factor)
    cleaned.data[integers] <- lapply(cleaned.data[integers], integer)
    cleaned.data[numerics] <- lapply(cleaned.data[numerics], numeric)
    str(cleaned.data)

    return("Function Complete")
}

此函数的干净且可重用的方法可能如下所示:

clean.data <- function(df, factors, integers, numerics, characters){
  if(!missing(factors)){
    df[factors] <- lapply(df[factors], as.factor)
  }
  if(!missing(integers)){
    df[integers] <- lapply(df[integers], as.integer)
  }
  if(!missing(numerics)){
    df[numerics] <- lapply(df[numerics], as.numeric)
  }
  if(!missing(characters)){
    df[characters] <- lapply(df[characters], as.character)
  }
  return(df)
}
这样你

可以将其与其他数据集重复使用, 灵活地选择要更改的变量类型 将从函数中获取更改后的数据集作为返回值。
这是错误的:lapplycleaned.data[integers],integer。还有下一行。此外,您的函数将返回字符串函数Complete,数据集已清理。数据将在退出时丢失。是的@RuiBarradas我理解,但函数在此之前失败-FUNX[[I]]中出错,…:无效的“长度”参数try as.factor、as.integer和as.numeric。错误实际上是tye向量整数、数值或因子之一不是映射到索引的整数,或者它们映射到的索引不在data.frame内。i、 e.大于列数。@ruibaradas感谢堆