【发布时间】:2016-01-11 05:08:04
【问题描述】:
我正在尝试使用通用函数对数据框的每一列进行操作,其中操作将根据列的类而有所不同。
我无法让函数访问列的名称,同时也将列分派到正确的方法。
df <- data.frame(f1 = factor(rep(1:3, 2)))
myfun <- function(x){
UseMethod("myfun", x)
}
myfun.factor <- function(x){
print("Using factor method")
print(names(x))
print(class(x))
}
myfun.default <- function(x){
print("Using default method")
print(names(x))
print(class(x))
}
作为列表应用会提供正确的调度,但会从列中删除名称
library(plyr)
l_ply(df, myfun)
[1] "Using factor method"
NULL
[1] "factor"
作为数组应用会保留名称,但不会给出正确的名称
a_ply(df, 2, myfun)
[1] "Using default method"
[1] "f1"
[1] "data.frame"
有没有一种巧妙的方法可以兼顾两者或am I stuck with the method described in the answer to this question?
【问题讨论】: