【问题标题】:Generate a list of factor columns生成因子列列表
【发布时间】:2019-02-18 16:28:47
【问题描述】:

我知道我可以使用sapply 来找出数据列的类别,如下所示:

sapply(data, class)

上面的代码类似于:How do I get the classes of all columns in a data frame?

但是,如何确定和存储属于 factor 类的列名向量 fac

【问题讨论】:

    标签: r class types


    【解决方案1】:

    fac <- names(data)[sapply(data, is.factor)]

    【讨论】:

    • 这给了你一个向量,但你提到你想要一个列表。你也可以试试as.list(names(data)[sapply(data, is.factor)]),除非你真正想要的是矢量:)
    • @AntoniosK 谢谢你的收获,我的意思是vector。已更正!
    【解决方案2】:

    另一种类似的方法是使用purrr 包:

    names(iris)[purrr::map_lgl(iris, is.factor)]
    #"Species"
    
    which(map_lgl(iris, is.factor) == TRUE) #this will return the column index as well.
    #Species 
    #5 
    

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 1970-01-01
      • 2019-01-22
      • 2018-06-15
      • 1970-01-01
      • 2023-01-31
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      相关资源
      最近更新 更多