r - 在之前使用过的R中使用count时出错

标签 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.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))
      
    }
测试
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

如果需要“浓度”的sum,则可以使用group_by操作代替count
freq.concentration <- function(df, Vars){
     df  %>% 
        group_by(across(all_of(Vars))) %>%
        summarise(n = n(), frequency.C = sum(concentration), .groups = 'drop')
   }
测试
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 

关于r - 在之前使用过的R中使用count时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64273972/

相关文章:

r - 在 R/Rmarkdown 中同步两个传单 map

mysql - 如何实现这个 COUNT(date > NOW()) AS 计数?

mysql - 使用 MATCH ... AGAINST 优化 COUNT(*)

mysql - 计算每个月登录的天数

linux - 用 gas 组装时 push 的指令后缀无效

r - 从父脚本中启动第二个 R 脚本

r - 当变量用于 `by` 时,.N 与长度(变量)不同

python - rpy2:加载conda环境下安装的R版本,不是系统中的那个

c++ - 将代码从一台机器复制到另一台机器会产生流浪字符

c - 如何修复 gcc 错误 : expected while before void