在R中使用以前工作的计数时出错
我使用了在R中使用以前工作的计数时出错,r,count,compiler-errors,R,Count,Compiler Errors,我使用了count来计算相同的行数并获得频率,它工作得很好,就像2小时前一样,现在它给了我一个我不理解的错误。我希望每次我有相同的行时,加上这些行的集中度。这是我的玩具数据和我的功能 df=data.frame(ID=seq(1:6),A=rep(0,6),B=c(rep(0,5),1),C=c(rep(1,5),0),D=rep(1,6),E=c(rep(0,3),rep(1,2),0),concentration=c(0.002,0.004,0.001,0.0075,0.00398,0.00
count
来计算相同的行数并获得频率,它工作得很好,就像2小时前一样,现在它给了我一个我不理解的错误。我希望每次我有相同的行时,加上这些行的集中度。这是我的玩具数据和我的功能
df=data.frame(ID=seq(1:6),A=rep(0,6),B=c(rep(0,5),1),C=c(rep(1,5),0),D=rep(1,6),E=c(rep(0,3),rep(1,2),0),concentration=c(0.002,0.004,0.001,0.0075,0.00398,0.006))
df
ID A B C D E concentration
1 1 0 0 1 1 0 0.00200
2 2 0 0 1 1 0 0.00400
3 3 0 0 1 1 0 0.00100
4 4 0 0 1 1 1 0.00750
5 5 0 0 1 1 1 0.00398
6 6 0 1 0 1 0 0.00600
freq.concentration=function(df,Vars){
df=data.frame(df)
Vars=as.character(Vars)
compte=count(df,Vars)
frequence.C= (compte$freq)/nrow(df)
output=cbind(compte,frequence.C)
return(output)
}
freq.concentration(df,colnames(df[2:6]))
# and here is the error that i get when i run the function which was working perfectly a while ago!
# Error: Must group by variables found in `.data`.
# * Column `Vars` is not found.
# Run `rlang::last_error()` to see where the error occurred.
PS:我不知道这是否相关,但当我打开一个脚本Rmd并将所有函数复制粘贴到此脚本时,我遇到了这个问题,突然我的函数停止工作。
我真的很感谢你事先的帮助。多谢各位
这是我在它正常工作时得到的输出:
output
ID A B C D E concentration.C.1 concentration.C.2
1 1 0 0 1 1 0 3 0.007
2 4 0 0 1 1 1 2 0.01148
3 6 0 1 0 1 0 1 0.00600
前3行是相似的,因此我们将3行的浓度相加,得到0.007,然后第4行和第5行是相同的,因此我们将它们的浓度相加,得到0.01148,最后一行是唯一的,因此浓度保持不变。我们可以转换为
sym
bol并进行计算(!
)在count
中,获取基于这些列的频率计数,然后获取'frequence.C'作为'n'与该计数的sum
的比例
library(dplyr)
freq.concentration <- function(df, Vars){
df %>%
count(!!! rlang::syms(Vars)) %>%
mutate(frequence.C = n/sum(n))
}
如果我们需要“浓度”的
sum
,我们可以使用groupby
操作而不是count
freq.concentration <- function(df, Vars){
df %>%
group_by(across(all_of(Vars))) %>%
summarise(n = n(), frequency.C = sum(concentration), .groups = 'drop')
}
freq.concentration%
分组依据(跨所有变量))%>%
总结(n=n(),频率.C=sum(浓度),.groups='drop')
}
-测试
freq.concentration(df,colnames(df)[2:6])
# A B C D E n frequence.C
#1 0 0 1 1 0 3 0.5000000
#2 0 0 1 1 1 2 0.3333333
#3 0 1 0 1 0 1 0.1666667
freq.concentration(df,colnames(df)[2:6])
# A tibble: 3 x 7
# A B C D E n frequency.C
# <dbl> <dbl> <dbl> <dbl> <dbl> <int> <dbl>
#1 0 0 1 1 0 3 0.007
#2 0 0 1 1 1 2 0.0115
#3 0 1 0 1 0 1 0.006
频率浓度(df,colnames(df)[2:6])
#一个tibble:3x7
#A B C D E n频率
#
#1 0 0 1 1 0 3 0.007
#2 0 0 1 1 1 2 0.0115
#3 0 1 0 1 0 1 0.006
它确实没有给出任何错误,但仍然没有给我想要的输出,我将添加我在帖子中的输出。@Janet我添加了频率。C。早些时候,我只是想显示错误在哪里。看一看,我编辑了这篇文章,以便您可以看到预期的输出。提前谢谢。@Janet我根据您新的Expected D输出更改了计算,假设它是浓缩的
和。@akrun谢谢@akrun实际上您给了我另一个问题的答案。如果一开始我不清楚,我道歉。我真的很感谢你的帮助。我要用你的两个答案!再次感谢你