【问题标题】:How can I create a table of variable names and their levels?如何创建变量名称及其级别的表?
【发布时间】:2020-02-21 10:07:37
【问题描述】:

我正在尝试制作一个包含两列的表格:1)变量名称,2)该变量的级别。

这是数据帧的虚拟代码:

Data <- data.frame(Gender = sample(c("male", "female", "other"),10, replace = TRUE), Age = sample(1:10), Happiness = sample(c("Very","Some","None"), 10, replace = TRUE))

所以本质上我只想要一个表格,上面写着:

变量名 |等级

性别 | 1=男性,2=女性,3=其他

年龄 |数字

幸福 | 1=非常,2=一些,3=无

请问我该怎么做?

【问题讨论】:

    标签: r


    【解决方案1】:

    基于 R 的想法可以是,

    data.frame(Levels = sapply(Data, function(i){i1 <- levels(i); 
                  ifelse(length(i1) > 0, paste0(seq_along(i1), ' = ', i1, collapse = ' '), class(i))}))
    
    #                                 Levels
    #Gender    1 = female 2 = male 3 = other
    #Age                             integer
    #Happiness    1 = None 2 = Some 3 = Very
    

    【讨论】:

    • @danibradford 如果此解决方案适合您,请考虑接受它(通过单击旁边的勾号),以便我们认为此问题已解决。谢谢
    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 2017-08-19
    • 1970-01-01
    相关资源
    最近更新 更多