as_factor works on columns but not on dataframe


I am trying to use as_factor to quickly convert survey data results into a dataframe to work with. But, when I use as_factor() on the df, nothing happens to the df... however,
if I use as_factor() on each column it seems to be working. I assume that the problem is one of the columns cant be converted to a factor and so none are being converted, but I have 100 columns so I need a solution to identify which column is the problem

sample <- data.frame(structure(list(Q8 = c("Core city of a smaller/medium region", 
"Core city of a smaller/medium region", "Core city of a rural region", 
"Inner ring or developed suburb", "Developing or outer suburb"
), Q35 = c("Below 50,000", "Below 50,000", "Below 50,000", "Below 50,000", 
"Below 50,000"), Q9_1 = c("Worsened Slightly", "Worsened Slightly", 
"Worsened Greatly", "Worsened Slightly", "Improved Slightly"), 
    Q9_2 = c("Worsened Slightly", "Worsened Slightly", "Worsened Slightly", 
    "Worsened Slightly", "Improved Slightly"), Q9_3 = c("Worsened Slightly", 
    "Worsened Slightly", "Worsened Slightly", NA, "Improved Slightly"
    ), Q48 = c("Manufacturing", "Healthcare", "Education", "Other", 
    "Manufacturing"), Q48_12_TEXT = c(NA, NA, NA, "Telemarketing", 
    NA), Q26_1 = c("Decreased", "No Change", "No Change", "No Change", 
    "Increased"), Q26_2 = c("Increased", "Don't Know/NA", "No Change", 
    "No Change", "Increased"), Q26_3 = c("No Change", "No Change", 
    "Increased", "Increased", "No Change"), Q26_4 = c("No Change", 
    "No Change", "Increased", "Don't Know/NA", "Increased")), row.names = c(NA, 
-5L), class = c("tbl_df", "tbl", "data.frame")))

sample <- as_factor(sample)
summary(sample) #so frustrating!

I was able to convert all to factors using mutate(across()) but I wonder why this happened when I can use as_factor on other dataframes?

Did you encounter any error when run sample <- as_factor(sample) like this?

#> Error in UseMethod("as_factor"): no applicable method for 'as_factor' applied to an object of class "function"

Created on 2021-04-14 by the reprex package (v2.0.0)

Based on the error, of course as_factor() (or as.factor()) only can be applied to a column. So if you use a dataframe as it's argumen it will give you error and can't convert all variables in a dataframe into factor at once.

1 Like

This topic was automatically closed 21 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.