Rename columns of a data frame by searching column name

后端 未结 4 1869
南旧
南旧 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.

提交回复
热议问题