r - 如何在 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
解决方案
不完全确定我是否得到你想要的,但我最好的猜测是如下所示
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()
您可以在过滤器函数中使用条件
推荐阅读
- javascript - smartsheet API 更新 PICKLIST 列错误
- php - 函数不会检测到数组值中包含的字符串
- docker - 泊坞窗:来自守护进程的错误响应:安装卷“”时出错:VolumeDriver.Mount:404 Not Found.(LINSTOR Docker Volume Plugin)
- ios - 如何使用 RealityKit 扫描二维码?
- bash - 在 Windows 上将 AWS CLI 与 MobaXterm 结合使用
- python - “错误:列表索引超出范围”在 952 个 xlsx 文件列表中,如何编辑然后另存为 csv
- machine-learning - 使用 Surprise 库时 SVD 的实际问题
- vue.js - 未捕获的 ReferenceError:未定义组件
- multithreading - Delphi“UI更新”线程提供的内容问题
- codesys - 防止局部变量保留