broccoli
broccoli

Reputation: 4846

Getting at grouping term from within ddply function?

I have the following example data frame x

id val
a 1
a 2
a 3
b 2
b 4
b 9

I have a simple function that I apply while doing my SAC. Something like,

f.x <- function(x){
 cat(x$id,"\n")
}

Note, all that I'm trying to do is print out the grouping term. This function is called using ddply as follows

ddply(x,.(id),f.x)

However, when I run this I get integer outputs which I suspect are indices of a list. How do I get the actual grouping term within f.x, in this case 'a' & 'b'? Thanks much in advance.

Upvotes: 2

Views: 227

Answers (2)

Wojciech Sobala
Wojciech Sobala

Reputation: 7561

If every thing you want to do is print you should use d_ply. In ddply (d_ply) actual argument passed to function (f.x here) is data.frame (subset of x data.frame), so you should modify your f.x function.

f.x <- function(x) cat(x[1,"id"],"\n")
d_ply(x,.(id),f.x)

Upvotes: 1

joran
joran

Reputation: 173727

Never be fooled into thinking that just because a variable looks like a bunch of characters, that it really is just a bunch of characters.

Factors are not characters. They are integer codes and will often behave like integer codes.

Coerce the values to character using as.character().

Upvotes: 4

Related Questions