[R] apply --> data.frame

Sam Steingold sds at gnu.org
Thu Aug 30 18:44:24 CEST 2012


> * Sam Steingold <fqf at tah.bet> [2012-08-30 08:56:17 -0400]:
>
> Is there a way for an apply-type function to return a data frame?
> the closest thing I think of is
>
>   foo <- as.data.frame(t(sapply(...)))
>   names(foo) <- c(....)

alas, this has a problem of creating a "homogeneous" data frame, i.e.,
all the columns are numbers or characters, because the function passed
to sapply returns c(....) and
> c(1,2,"a")
[1] "1" "2" "a"

e.g.,
as.data.frame(t(sapply(c("a,1","b,2","c,3"),function (n) strsplit(n,",")[[1]])))
    V1 V2
a,1  a  1
b,2  b  2
c,3  c  3

'data.frame':	3 obs. of  2 variables:
 $ V1: Factor w/ 3 levels "a","b","c": 1 2 3
  ..- attr(*, "names")= chr  "a,1" "b,2" "c,3"
 $ V2: Factor w/ 3 levels "1","2","3": 1 2 3
  ..- attr(*, "names")= chr  "a,1" "b,2" "c,3"

I wanted the V1 column to be a string, and V2 to be a number.
(I know stringsAsFactors=FALSE would replace factors with strings, but I
need a string and a number)

I could, of course, do ret$V2 <- as.numeric(ret$V2) but this would mean
a double conversion: from number to string first (by c()) and then back.

thanks.

-- 
Sam Steingold (http://sds.podval.org/) on Ubuntu 12.04 (precise) X 11.0.11103000
http://www.childpsy.net/ http://mideasttruth.com http://truepeace.org
http://openvotingconsortium.org http://ffii.org http://www.memritv.org
Diplomacy is the art of saying "nice doggy" until you can find a nice rock.




More information about the R-help mailing list