1

I have made the following script to sum rows of a data frame and count number of columns that are not zero for all rows. Suddenly my script stop working and I am not sure what the error is.

    test <- structure(list(col1 = c(0.126331200264469, 0, 0, 0, 0), col2 = c(0, 
0, 0, 0, 0), col3 = c(0, 0, 0, 0, 0), col4 = c(0, 0, 0, 0, 0), 
    col5 = c(0, 0, 0, 0, 0)), row.names = c("row1", "row2", "row3", 
"row4", "row5"), class = "data.frame")

script:

test.out <- test %>% 
  mutate(Not_Present = across(everything(), ~ . == 0) %>% 
           reduce(`+`), Present = ncol(test)- Not_Present)

error:

Error: `across()` must only be used inside dplyr verbs.
Run `rlang::last_error()` to see where the error occurred.
user2300940
  • 2,355
  • 1
  • 22
  • 35

2 Answers2

2

If it helps in any way for further work, I would just go with:

test.out <- sum(apply(test !=0, 2, any))
2

Another option is using rowSums

library(dplyr)
test %>% 
   mutate(Not_Present = rowSums(across(everything()) == 0), 
          Present = ncol(test) - Not_Present)
akrun
  • 874,273
  • 37
  • 540
  • 662