Search code examples
rr-factor

R data frame factor levels


I have this code snippet:

levels(testing[,c('is_top_rated_listing')])

which returns :

NULL

however this code returns:

levels(testing$is_top_rated_listing)

returns

"0" "1"

Unfortunately I need to use the first approach since the column name dynamically changes. Any idea how can I utilize the first approach ?

dput output:

 structure(list(seller_feedback_score = c(321350, 138351, 282470, 
1596, 275283, 275283), is_top_rated_listing = structure(c(2L, 
1L, 2L, 1L, 2L, 1L), .Label = c("0", "1"), class = "factor"), 
    seller_is_top_rated_seller = c(1L, 0L, 1L, 0L, 1L, 1L), is_auto_pay = structure(c(2L, 
    2L, 2L, 2L, 2L, 2L), .Label = c("0", "1"), class = "factor"), 
    is_returns_accepted = structure(c(2L, 1L, 2L, 2L, 2L, 2L), .Label = c("0", 
    "1"), class = "factor"), seller_feedback_rating_star = c("RedShooting", 
    "RedShooting", "RedShooting", "Red", "RedShooting", "RedShooting"
    ), keywords_title_assoc = c(1, 0.666666666666667, 1, 0.333333333333333, 
    1, 1), normalized.price_shipping = c(0.0780598804064508, 
    0.0883814448796398, 0.0780598804064508, 0.0777079296934893, 
    0.0254380218279135, 0.0777079296934893), seller_feedback_score_rank = c(9504L, 
    28866L, 19445L, 50280L, 21796L, 21796L), seller_positive_feedback_percent_rank = c(15L, 
    9L, 10L, 4L, 5L, 5L), item_condition = structure(c(1L, 1L, 
    1L, 1L, 1L, 1L), .Label = c("New", "New other (see details)"
    ), class = "factor"), rank = c(9L, 11L, 13L, 21L, 3L, 4L)), .Names = c("seller_feedback_score", 
"is_top_rated_listing", "seller_is_top_rated_seller", "is_auto_pay", 
"is_returns_accepted", "seller_feedback_rating_star", "keywords_title_assoc", 
"normalized.price_shipping", "seller_feedback_score_rank", "seller_positive_feedback_percent_rank", 
"item_condition", "rank"), class = c("tbl_df", "data.frame"), row.names = c(NA, 
-6L))

Solution

  • Here's the answer:

    levels(testing[,col][[1]])
    

    I'm glad I answered my first stack Q :-)