代码之家  ›  专栏  ›  技术社区  ›  gaut

如何在ddply函数中使用字符串?

  •  -1
  • gaut  · 技术社区  · 7 年前

    就像一个示例,创建一个类似于 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
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Shinobi_Atobe    7 年前

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

    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()
    

    您可以在filter函数中处理条件

        2
  •  -1
  •   gaut    6 年前

    好吧,我找到了方法。我想不是很优雅,但谁在乎:

    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)也可以