简体   繁体   English

从ddply函数中获取分组术语?

[英]Getting at grouping term from within ddply function?

I have the following example data frame x 我有以下示例数据框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. 我在执行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调用此函数,如下所示

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 fx, in this case 'a' & 'b'? 如何在fx中获得实际的分组项,在这种情况下为“ a”和“ b”? Thanks much in advance. 在此先感谢。

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(). 使用as.character()将值强制转换为字符。

If every thing you want to do is print you should use d_ply. 如果您想做的每件事都是打印,则应使用d_ply。 In ddply (d_ply) actual argument passed to function (fx here) is data.frame (subset of x data.frame), so you should modify your fx function. 在ddply(d_ply)中,传递给函数(此处为fx)的实际参数是data.frame(x data.frame的子集),因此您应该修改fx函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM