Re: [R] class in apply

From: Omar Lakkis <uofiowa_at_gmail.com>
Date: Thu 21 Jul 2005 - 00:36:52 EST

Thank you for teh helpful answer. I do have one aother related question; If I am not interested in teh result of the lapply, as I am using it instaid of a for loop, example

lapply(df, function(r) sqlQuery(conn, paste("insert into t values(",r['a'],',',r['b'],')')))

and I am not interested in teh result of the insert sql statement. Is it, for memory and other concerns better to do it this way or to implement a for loop?

for (i in seq(length= nrow(df)) {

   sqlQuery(conn, paste("insert into t values(",df[i,'a'],',',df[i,'b'],')'))) }

On 7/20/05, Stéphane Dray <dray@biomserv.univ-lyon1.fr> wrote:
> apply transorm your data.frame into a matrix which can contains only one
> type of values (character or numeric or logical).
> data.frame are list, so they can contain various kind of data, and a
> solution to your problem is given by lapply:
>
> > b=lapply(df, function(r) print(class(r['a'])))
> [1] "numeric"
> [1] "factor"
>
> >Numeric data that is part of a mixed type data frame is converted into
> >character. How can I tell apply to maintain the original class of a
> >column and not convert it into character. I would like to do this of
> >the vector and not inside the apply function individually over each
> >element. Consider the following two scenarios, in the second column
> >'a' maintained its class while it lost its numeric type in the first
> >case.
> >
> >
> >
> >>df = data.frame(a=c(1,2), b=c('A','B'))
> >>df
> >>
> >>
> > a b
> >1 1 A
> >2 2 B
> >
> >
> >>a=apply(df, 1, function(r) print(class(r['a'])))
> >>
> >>
> >[1] "character"
> >[1] "character"
> >
> >
> >>a=apply(df, 1, function(r) print(class(r['b'])))
> >>
> >>
> >[1] "character"
> >[1] "character"
> >
> >
> >
> >
> >>df = data.frame(a=c(1,2))
> >>df
> >>
> >>
> > a
> >1 1
> >2 2
> >
> >
> >>a=apply(df, 1, function(r) print(class(r['a'])))
> >>
> >>
> >[1] "numeric"
> >[1] "numeric"
> >
> >______________________________________________
> >R-help@stat.math.ethz.ch mailing list
> >https://stat.ethz.ch/mailman/listinfo/r-help
> >PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
> >
> >
> >
> >
>
>
> --
> Stéphane DRAY (dray@biomserv.univ-lyon1.fr )
> Laboratoire BBE-CNRS-UMR-5558, Univ. C. Bernard - Lyon I
> 43, Bd du 11 Novembre 1918, 69622 Villeurbanne Cedex, France
> Tel: 33 4 72 43 27 57 Fax: 33 4 72 43 13 88
> http://www.steph280.freesurf.fr/
>
>



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Thu Jul 21 00:43:31 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:33:51 EST