Xodarap
Xodarap

Reputation: 11849

How can I use a frame in apply?

I really like using the frame syntax in R. However, if I try to do this with apply, it gives me an error that the input is a vector, not a frame (which is correct). Is there a similar function to mapply which will let me keep using the frame syntax?

df = data.frame(x = 1:5, y = 1:5)

# This works, but is hard to read because you have to remember what's
# in column 1 
apply(df, 1, function(row) row[1])

# I'd rather do this, but it gives me an error
apply(df, 1, function(row) row$x)

Upvotes: 1

Views: 58

Answers (1)

agstudy
agstudy

Reputation: 121608

Youcab't use the $ on an atomic vector, But I guess you want use it for readability. But you can use [ subsetter.

Here an example. Please provide a reproducible example next time. Question in R specially have no sense without data.

set.seed(1234)
gidd <- data.frame(region=sample(letters[1:6],100,rep=T),
                   wbregion=sample(letters[1:6],100,rep=T),
                   foodshare=rnorm(100,0,1),
                   consincPPP05 = runif(100,0,5),
                   stringsAsFactors=F)

  apply(gidd, ## I am applying it in all the grid here!
          1, 
        function(row) {
        similarRows = gidd[gidd$wbregion == row['region'] &
                         gidd$consincPPP05 > .8 * as.numeric(row['consincPPP05']),
                       ]
    return(mean(similarRows$foodshare))
  })

Note that with apply I need to convert to a numeric.

You can also use plyr or data.table for a clean syntax , for example:

  apply(df,1,function(row)row[1]*2)

is equivalent to

  ddply(df, 1, summarise, z = x*2)

Upvotes: 2

Related Questions