开发者

aaply fails on a vector

开发者 https://www.devze.com 2023-02-17 02:13 出处:网络
I am trying to understand how to use the excellent plyr p开发者_如何转开发ackage\'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.

I am trying to understand how to use the excellent plyr p开发者_如何转开发ackage'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!


If you want to use plyr on a vector, you have to use l*ply, as follows:

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

In other words, sapply and laply are equivalent

0

精彩评论

暂无评论...
验证码 换一张
取 消