【问题标题】:In R: How to delete specific string in specific column names在 R 中:如何删除特定列名中的特定字符串
【发布时间】:2021-10-05 03:59:39
【问题描述】:

数据清理任务

我有一个数据框 df 有 1000 列,每列名称以 X_ 开头。我只想删除前 30 列中的X_

X_col1,X_col2,X_col3,X_col4,X_col5,.....,X_col1000.

期望的输出:

col1,col2,col3,col4,col5,col6,.....,col30 ; X_col31,X_col32,.....,X_col1000

X_ 仅应在 X_col1X_col30 中删除,同时将 X_col31 保留到 X_col1000

在 R 中尝试

names(df) <- gsub("X_", "", names(df)) # this removes `X_` in all 1000 columns, I only want the first 30 columns

谢谢

【问题讨论】:

  • sub("^X_(?=col(?:[1-9]|[12][0-9]|30)(?!\\d))", "", names(df), perl=TRUE)?见this regex demo

标签: r string dataframe gsub


【解决方案1】:

我觉得这样就可以了

colnames(df)[1:30] <- gsub("X_", "", colnames(df)[1:30])

【讨论】:

    猜你喜欢
    • 2022-08-16
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 2014-03-05
    • 1970-01-01
    • 2019-04-25
    • 2014-04-10
    相关资源
    最近更新 更多