【发布时间】:2011-03-11 01:13:47
【问题描述】:
我在网上找不到这个问题的解决方案,虽然看起来很简单。 就是这样:
#Construct test dataframe
tf <- data.frame(1:3,4:6,c("A","A","A"))
#Try the apply function I'm trying to use
test <- apply(tf,2,function(x) if(is.numeric(x)) mean(x) else unique(x)[1])
#Look at the output--all columns treated as character columns...
test
#Look at the format of the original data--the first two columns are integers.
str(tf)
一般来说,我想根据行/列包含的数据类型来区分我 apply 在行/列上的哪个函数。
在这里,如果列是数字列,我想要一个简单的mean,如果列是字符列,我想要一个简单的unique 值。如您所见,apply 将所有列视为字符,就像我编写此函数的方式一样。
【问题讨论】: