保持类型适用

时间:2017-10-29 21:34:07

标签: r

当我使用apply时,似乎类型总是强制转换为character - 我想根据类型对列进行不同的反应,是否有任何方法可以保留类型或类似的函数呢?

calculate_stats = function(data, divideby){
  print(typeof(data)) # Always prints character!
}

get_result_table = function(data, divideby){
  apply(data, 2, calculate_stats, divideby = divideby)
}

get_result_table(iris, iris$Species)

2 个答案:

答案 0 :(得分:0)

来自colwise包的

plyr就是这样做的。

答案 1 :(得分:0)

继上面的评论之后,如果你定义

get_result_table = function(data, divideby) {
    sapply(data, calculate_stats, divideby = divideby)
}

你得到了

get_result_table(iris, iris$Species)
#[1] "double"
#[1] "double"
#[1] "double"
#[1] "double"
#[1] "integer"
#Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species
#    "double"     "double"     "double"     "double"    "integer"

也许这更符合您的期望?