1

我试图编写如下函数:

Q5base_func<- function(x){
  a<-subQ5 %>% group_by(Q1,x) %>% summarise(n = n())
  a <- a[complete.cases(a),] %>% filter(x == 1)
  sum <- sum(a$n)
  a_percent<- a%>%
    mutate(freq= (n/sum)*100)
}

我希望在 x==1 时获得 x 的数量以及百分比

有人能指出我错在哪里吗?谢谢!

当我应用该功能时,

Q5base_func(subQ5$Q4)

错误回溯:

 Error: Column `x` is unknown 
13.
stop(structure(list(message = "Column `x` is unknown", call = NULL, 
    cppstack = NULL), class = c("Rcpp::exception", "C++Error", 
"error", "condition"))) 
12.
grouped_df_impl(data, unname(vars), drop) 
11.
grouped_df(groups$data, groups$group_names, .drop) 
10.
group_by.data.frame(., Q1, x) 
9.
group_by(., Q1, x) 
8.
function_list[[i]](value) 
7.
freduce(value, `_function_list`) 
6.
`_fseq`(`_lhs`) 
5.
eval(quote(`_fseq`(`_lhs`)), env, env) 
4.
eval(quote(`_fseq`(`_lhs`)), env, env) 
3.
withVisible(eval(quote(`_fseq`(`_lhs`)), env, env)) 
2.
subQ5 %>% group_by(Q1, x) %>% summarise(n = n()) 
1.
Q5base_func(subQ5$Q11) 

示例数据集是这样的:

Q1  Qx
1   1
2   0
2   1
3   0
3   1
3   1
4

1 回答 1

0

你想要完成的事情是可能的。

subQ5 <- structure(list(Q1 = c(1L, 2L, 2L, 3L, 3L, 3L), 
                    Qx = c(1L, 0L, 1L, 0L, 1L, 1L)), 
               class = "data.frame", row.names = c(NA, -6L))

library(dplyr)

Q5base_func <- function(df, x) {
   df %>% filter(complete.cases(.))  %>% 
   group_by(Q1) %>% 
 #  mutate(sumx=sum(Qx==x), percent=sum(Qx==x)/n())     #add columns and keeps all of the data
    summarise(sumx=sum(Qx==x), percent=sum(Qx==x)/n())  #summarize the results
}

x<-1
answer <-Q5base_func(subQ5, x)
answer
于 2020-09-20T20:08:18.853 回答