On Feb 23, 2011, at 4:11 AM, Patrick Hausmann wrote:
> Dear list,
>
> this works fine:
>
> x <- split(iris, iris$Species)
> x1 <- lapply(x, function(L) transform(L, g = L[,1:4] * 3))
>
> but I would like to multiply each Species with another factor:
You will probably confuse yourself by not adopting R terminology. A
"factor" on R is an object with discrete categories and is not
something that is subject to multiplication.
> setosa by 2, versicolor by 3 and virginica by 4. I've tried mapply
> but without success.
Furthermore in this case you must mean something less general than
"multiply"-ing every vector in each of those levels of "x"
since one
of the vectors is an R "factor".
This is not a clean solution since there are in each of the levels
that Species factor which when multiplied returns "NA", but the rest
of the vectors survive the process with the intended ratio to the
original:
res <- sapply(2:4, function(z) mapply("*", x[z-1] ,
MoreArgs=list(z)))
You could make this a bit clean by not including Species in the levels
of the split:
x <- split(iris[1:4], iris$Species)
Then the above would be free of those NA values, but it would be
stripped of the identifying labels. You could also use mapply and get
an index-able matrix each of whose values in the new "x" is a vector:
res <- mapply("*", x, 2:4)
> res["Sepal.Length", "setosa"]
[[1]]
[1] 10.2 9.8 9.4 9.2 10.0 10.8 9.2 10.0 8.8 9.8 10.8 9.6
9.6 8.6 11.6 11.4 10.8 10.2 11.4
[20] 10.2 10.8 10.2 9.2 10.2 9.6 10.0 10.0 10.4 10.4 9.4 9.6 10.8
10.4 11.0 9.8 10.0 11.0 9.8
[39] 8.8 10.2 10.0 9.0 8.8 10.0 10.2 9.6 10.2 9.2 10.6 10.0
>
> Any thoughts? Thanks for any idea!
> Patrick
>
> ______________________________________________
> 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.
David Winsemius, MD
West Hartford, CT