我在网上找不到这个问题的解决方案,看起来很简单。这是它:
#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
按照我编写此函数的方式将所有列视为字符。