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 回答