首页 > 解决方案 > 如何在 ddply 函数中使用字符串?

问题描述

作为一个说明性示例,要创建类似于countif在 excel 中的函数,这是我尝试在下面的 ddply“countif”变量定义中以某种方式使用字符串“mycolumn”的方法:

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有效,但我需要一种方法能够mycolumn在 ddply 函数中使用我的字符串,而不是仅仅依赖nrow. 非常感谢。

> 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

标签: rdplyr

解决方案


不完全确定我是否得到你想要的,但我最好的猜测是如下所示

library(dplyr)

df <-  data.frame(mycolumn = c("a","a","b","c","c"))

result1 <- df %>% group_by(mycolumn) %>% tally()

result3 <- df %>% filter(mycolumn %in% c("a", "b")) %>% group_by(mycolumn) %>% tally()

您可以在过滤器函数中使用条件


推荐阅读