0

I am trying to understand how to use the excellent plyr package's commands on a vector (in my case, of strings). I suppose I'd want to use aaply, but it fails, asking for a margin. But there aren't columns or rows in my vector!

To be a bit more concrete, the following command works, but returns results in a wierd list. states.df is a data frame, and region is the name of the state (returned using Hadley's map_data("state") command). Thus, states.df$region is a vector of strings (specifically, state names). opinion.new is a vector of numbers, named using state names.

states.df <- map_data("state")
ch = sapply(states.df$region, function (x) { opinion.new[names(opinion.new)==x] } )

What I'd like to do is:

ch = aaply(states.df$region, function (x) { opinion.new[names(opinion.new)==x] } )

Where ch is the vector of numbers looked up or pulled from opinion.new. But aaply requires an array, and fails on a vector.

Thanks!

4

1 に答える 1

5

ベクトルで plyr を使用する場合は、次のように l*ply を使用する必要があります。

v <- 1:10
sapply(v, function(x)x^2)
 [1]   1   4   9  16  25  36  49  64  81 100

laply(v, function(x)x^2)
 [1]   1   4   9  16  25  36  49  64  81 100

つまり、sapply と laply は同等です。

于 2011-03-16T22:55:58.800 に答える