Home > Mobile >  Error: Join columns must be present in data. x Problem with `column1` and `column2`
Error: Join columns must be present in data. x Problem with `column1` and `column2`

Time:12-07

I got error for this function, when I change colum1-column3 with var1-var3 it works ,it's bizarre:

var1<-c(rep("A",4),rep("B",4))
var2<-c(rep("C",4),rep("D",4))
var3<-c(rep("E",2),rep("F",4),rep("G",2))
dataset<-data.frame(var1,var2,var3)


Rfun<-function(data,column1,column2,column3){
  data<- data %>%
    mutate(n = 1, column3 = str_c('column3_', column3)) %>% 
    complete(column1, column2, column3, fill = list(n = 0)) %>% 
    pivot_wider(names_from = column3, values_from = n, values_fn = sum) %>% 
    mutate(Total = rowSums(across(where(is.numeric)))) %>% 
    group_by(column1) %>% 
    mutate(across(starts_with('column3'), 
                  ~ case_when(. == 0 ~ '0(0%)', 
                              TRUE ~ sprintf('%d(%d%%)', .,  100 * mean(. != 0))))) %>% 
    ungroup
  
  print(data)
  
  return(data)
}

Rfun(dataset,var1,var2,var3)

this the error:

enter image description here

CodePudding user response:

Consider using {{}} to evaluate

Rfun<-function(data,column1,column2,column3){
   data %>%
    mutate(n = 1, {{column3}} := str_c('column3_', {{column3}})) %>% 
    complete({{column1}}, {{column2}}, {{column3}}, fill = list(n = 0)) %>% 
    pivot_wider(names_from = {{column3}}, values_from = n, values_fn = sum) %>% 
    mutate(Total = rowSums(across(where(is.numeric)))) %>% 
    group_by({{column1}}) %>%
    mutate(across(starts_with('column3'), 
                  ~ case_when(. == 0 ~ '0(0%)', 
                      TRUE ~ sprintf('%d(%d%%)', .,  100 * mean(. != 0)))))  %>%
    ungroup
    
  
  
}

-testing

Rfun(dataset,var1,var2,var3)
# A tibble: 4 × 6
  var1  var2  column3_E column3_F column3_G Total
  <chr> <chr> <chr>     <chr>     <chr>     <dbl>
1 A     C     2(50%)    2(50%)    0(0%)         4
2 A     D     0(0%)     0(0%)     0(0%)         0
3 B     C     0(0%)     0(0%)     0(0%)         0
4 B     D     0(0%)     2(50%)    2(50%)        4
  • Related