【问题标题】:How can I use strings inside ddply functions?如何在 ddply 函数中使用字符串?
【发布时间】:2023-03-30 12:50:02
【问题描述】:

作为一个说明性示例,要在 excel 中创建类似于 countif 的函数,我尝试在下面的 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 有效,但我需要一种能够在 ddply 函数中使用我的mycolumn 字符串的方法,而不是仅仅依赖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

【问题讨论】:

  • 你研究过 do() 吗?
  • 您能详细说明一下吗?在这种情况下我将如何使用它?
  • 您要查找的 'if' 是什么?看来您只是按组计算它们(我的专栏)。使用 group_by() 和 summarise() 可以获得相同的结果。
  • 是的,我想还有其他方法,但是对于其他功能,我需要了解如何将“mycolumn”转换为 ddply 可以理解的 mycolumn。
  • @gpier ddply 有点过时了,你会发现它的后继者更容易使用:dplyrtidyr(通常称为tidyversehave alook here

标签: r dplyr


【解决方案1】:

不完全确定我是否得到了你想要的东西,但我最好的猜测是像下面这样的

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

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

【讨论】:

  • 是的,我想还有其他方法,但是对于其他功能,我需要了解如何将“mycolumn”转换为 ddply 可以理解的 mycolumn。嘿,我可以在 ddply 中使用字符串吗...
  • 要得到与 ddply 相同的结果,那么你将如何将 result1 重新组合到 df 中?
【解决方案2】:

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

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) 也可以正常工作

【讨论】:

  • 我觉得如果你在几周后回到这段代码,你会完全被它弄糊涂——你真的应该像上面建议的那样研究 tidyverse
  • 感谢您的建议。我喜欢 ddply 因为它是单行的,但绝对是开放的,请参阅我关于将结果重新组合到 df 中的另一个问题...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-07
  • 1970-01-01
  • 1970-01-01
  • 2021-05-07
  • 2012-05-18
  • 2014-11-19
相关资源
最近更新 更多