Dear list,

I couldn't find a solution for this problem online, as simple as it seems.
Here's the problem:


#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)


In general terms, I want to differentiate what function I apply over a
row/column based on what type of data that row/column contains. Here I want
a simple mean if the column is numeric, and the first unique value if the
column is a character column. As you can see, 'apply' treats all columns as
characters the way I've written his function.

Any thoughts? Many thanks in advance,
Aaron

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to