R 数据框因子级别

R data frame factor levels

我有这个代码片段:

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

其中 returns :

NULL

但是这段代码 returns:

levels(testing$is_top_rated_listing)

returns

"0" "1"

不幸的是,我需要使用第一种方法,因为列名是动态变化的。 知道如何使用第一种方法吗?

dput输出:

 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))

答案如下:

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

很高兴回答了我的第一个堆栈问题:-)