Rename columns of a data frame by searching column name

后端 未结 4 1868
南旧
南旧 2021-02-06 14:44

I am writing a wrapper to ggplot to produce multiple graphs based on various datasets. As I am passing the column names to the function, I need to rename the column names so tha

相关标签:
4条回答
  • 2021-02-06 14:57
    > names(df)[grep("^col", names(df))] <- 
                            paste("new", names(df)[grep("^col", names(df))], sep="_")
    > names(df)
    [1] "new_col1" "new_col2" "new_col3"
    

    If you want to replace an ordered set of column names with an arbitrary character vector, then this should work:

    names(df)[sapply(oldNames, grep, names(df) )] <- newNames
    

    The sapply()-ed grep will give you the proper locations for the 'newNames' vector. I suppose you might want to make sure there are a complete set of matches if you were building this into a function.

    0 讨论(0)
  • 2021-02-06 15:05
    require(plyr)
    df <- data.frame(col2=1:3,col1=3:5,col3=6:8)
    df <- rename(df, c("col1"="new_col1", "col2"="new_col2", "col3"="new_col3"))
    df
    

    And you can be creative in making that second argument to rename so that it is not so manual.

    0 讨论(0)
  • 2021-02-06 15:08

    hmm, this might be way to complicated, but the first that come into my mind:

    lookup <- data.frame(search = c(col3_search,col2_search,col1_search),
                         replace = c(col3_replace,col2_replace,col1_replace))
    
    colnames(df) <- lookup$replace[match(lookup$search, colnames(df))]
    
    0 讨论(0)
  • 2021-02-06 15:15

    I second @justin's aes_string suggestion. But for future renaming you can try.

    require(stringr)
    df <- data.frame(col1=1:3,col2=3:5,col3=6:8)
    oldNames <- c("col1", "col2", "col3")
    newNames <- c("new_col1", "new_col2", "new_col3")
    names(df) <- str_replace(string=names(df), pattern=oldNames, replacement=newNames)
    
    0 讨论(0)
提交回复
热议问题