【发布时间】: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有点过时了,你会发现它的后继者更容易使用:dplyr,tidyr(通常称为tidyverse,have alook here