Non-numeric-alike variable(s) in data frame

In the code below I select DR columns that are equal to zero.

r <- data.frame(DR01 = 3, DR02 = 4, DR03 = 0, DR04 = 0) 

names(rev(r)[, cumsum(rev(r)) == 0])

[1] "DR04" "DR03

However, I have a new database with more information, but when I do this: names(rev(r)[, cumsum(rev(r)) == 0]) gives an error.

So how to tweak the code to fix this error? I believe I need to select only DR columns, am I correct?

r <- data.frame(date1= "2021-06-28",date2="2021-06-28",Category="ABC", DR01 = 3, DR02 = 4, DR03 = 0, DR04 = 0) 

names(rev(r)[, cumsum(rev(r)) == 0])

Error in Math.data.frame(rev(r)) : 
  non-numeric-alike variable(s) in data frame: Category, date2, date1

You can select the numeric columns with functions from dplyr. You could also use starts_with("DR") in the select function.

library(dplyr)
r <- data.frame(date1= "2021-06-28",date2="2021-06-28",Category="ABC", 
                DR01 = 3, DR02 = 4, DR03 = 0, DR04 = 0)
ZeroFunc <- function(V){
  sum(V) == 0
}
r |> select(where(is.numeric)) |> 
  select(where(ZeroFunc)) |>
  names() |> rev()
#> [1] "DR04" "DR03"

Created on 2022-03-30 by the reprex package (v2.0.1)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.