如何在ddply函数中使用字符串? [英] How can I use strings inside ddply functions?

查看:60
本文介绍了如何在ddply函数中使用字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅作为示例,在excel中创建类似于 countif 的函数,这就是我试图以某种方式在ddply中使用字符串 mycolumn的内容, countif变量定义如下:

Just as an illustrative example, to create a function similar to countif in excel, here is what I have tried to somehow use the string "mycolumn" inside the ddply "countif" variable definition below:

df <- c("a","a","b","c","c") %>% data.frame(stringsAsFactors = F)
colnames(df) <- "mycolumn"
x <- "mycolumn"
countif <- function(df,x ) {
y <- which(colnames(df)==x)
result1 <- ddply(df,x,nrow) #this works, but I can't use the x argument
result2 <- ddply(df,x,summarise, countif=length(df[,y])) #not working
result3 <- ddply(df,x,summarise, countif=length(parse(text=x))) #not working
    }

当您可以在下面看到,只有 result1 有效,但是我需要一种方法来在ddply中使用我的 mycolumn 字符串功能,而不是仅依靠 nrow 。非常感谢。

As you can see below, only result1 works, but I need a way to be able to use my mycolumn string in the ddply function instead of solely relying on nrow. Many thanks.

> result1
  mycolumn V1
1        a  2
2        b  1
3        c  2
> result2
  mycolumn countif
1        a       5
2        b       5
3        c       5
> result3
  mycolumn countif
1        a       1
2        b       1
3        c       1


推荐答案

好的,我找到了一种方法。我猜不是那么优雅,但是谁在乎呢?

OK, I found a way. Not so elegant I guess, but who cares:

countif <- function(df,x ) {
df$myartificialname <- df[,which(colnames(df)==x)]
result <- ddply(df,x,summarise,countif=length(myartificialname) )
print(paste(length(unique(result$countif)), "levels counted:", toString(head(unique(result$countif)))))
return(result$countif)
}

编辑:实际上get(x)也可以正常工作

actually get(x) would work fine as well

这篇关于如何在ddply函数中使用字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆