我无法在线找到此问题的解决方案,就像看起来那么简单。 这里,它是:将数字视为字符
#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
将所有列视为我写这个函数的方式。
这正是答案 - 谢谢!欢呼所有贡献:) – Aaron
我忘了添加'stringsToFactors = FALSE',因为列'c'的类默认为'factor'。你可能想要设置'options(stringsAsFactors = FALSE)',否则,你会得到一个'factor'。被告知。 – aL3xa