apply --> data.frame
?lapply
z <-data.frame(a=1:3,b=letters[1:3])
lapply(z,"[",1:2)
$a [1] 1 2 $b [1] a b Levels: a b c
data.frame(lapply(z,"[",1:2)) ## Is this not what you want?
a b 1 1 a 2 2 b You really should spend a little more time with the docs figuring out what R _does_ and a little less complaining about what you think R cannot do. -- Bert
On Thu, Aug 30, 2012 at 9:44 AM, Sam Steingold <sds at gnu.org> wrote:
* 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.
______________________________________________ R-help at 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.
Bert Gunter Genentech Nonclinical Biostatistics Internal Contact Info: Phone: 467-7374 Website: http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm