【问题标题】:Subset data to contain only label of columns whose names match a condition子集数据以仅包含名称与条件匹配的列的标签
【发布时间】:2022-02-07 12:33:41
【问题描述】:

我有以下示例数据框:

M <- c(1, 2)
S <- c(3, 4)
old_df <- data.frame(M, S)
label(old_df$M) <- "My Mathematics Variable"
label(old_df$S) <- "My Science Variable"

我想过滤,以便在列的标签中只包含包含“数学”的列。

谢谢!

【问题讨论】:

    标签: r regex subset contains hmisc


    【解决方案1】:

    你可以使用grepl:

    old_df[, grepl("Math", label(old_df))]
    # My Mathematics Variable 
    # [1] 1 2
    

    数据

    library(Hmisc)
    old_df <- structure(list(M = structure(c(1, 2), label = "My Mathematics Variable", class = c("labelled", 
    "numeric")), S = structure(c(3, 4), label = "My Science Variable", class = c("labelled", 
    "numeric"))), row.names = c(NA, -2L), class = "data.frame")
    

    【讨论】:

    • 在这种情况下,有效,但我猜在我的原始数据集中,标签不是“字符串格式”。当我使用相同的代码时,所有列都会消失
    • 我不确定我理解你的意思。您能否编辑您的问题并添加一个解决方案不起作用的最小示例?
    猜你喜欢
    • 2013-09-06
    • 2022-08-19
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    相关资源
    最近更新 更多