【问题标题】:How to Use lapply with grep to delete columns in list set如何使用 lapply 和 grep 删除列表集中的列
【发布时间】:2018-03-18 18:14:59
【问题描述】:

对于我的生活,我无法弄清楚如何通过我的列表 lapply 来 grep 列名。

这是适用于一个数据帧的代码:

tl1 <- trend1[,grep("Date|AIR|LSL",colnames(trend1))]

但我有trend1trend12。如何将其转换为列表并将 grep 应用于列表的每个元素以获取 tl1 到 tl12 数据帧?

或者,我愿意使用 for 循环。

【问题讨论】:

  • 假设您已将trend1 到12 放在一个列表中,那么lapply(list_of_dfs, function(df) df[,grep("Date|AIR|LSL",colnames(df))]) 应该可以。

标签: r regex lapply


【解决方案1】:

假设您的 R 环境中已经有 trend1trend12 数据框,您可以将它们全部放在一个列表中并使用 lapply 删除您不需要的列:

# mget gets the dataframes whose names are returned by ls
list_of_dfs <- mget(ls(pattern="trend\\d{1,2}"))

# loop through the dataframes and make the changes
new_dfs <- lapply(list_of_dfs, function(df) df[,grep("Date|AIR|LSL",colnames(df))])

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2017-04-04
    • 2014-01-18
    • 2015-05-30
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多