1
我試圖使用通用函數來操作數據框的每一列,其中操作將根據列的類而不同。使用plyr和通用函數來操作數據幀的每一列,同時保留名稱
我無法賦予函數對列的名稱的訪問權限,同時也將列分派給正確的方法。
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?