简体   繁体   中英

Replacing a string in column names in dataframe in R with grepl

I have a dataframe and some of the columns begin with 'dfall$PROFESSION' which I want to delete. Ie:

"dfall$PROFESSIONBusinessman"             "dfall$PROFESSIONDoctor"                 
[35] "dfall$PROFESSIONEngineer"                "dfall$PROFESSIONFarmer"                 
[37] "dfall$PROFESSIONHousewife"               "dfall$PROFESSIONLawyer"                 
[39] "dfall$PROFESSIONMissing"                 "dfall$PROFESSIONPensioner"

So I tried:

names(df_all) <- gsub("dfall$PROFESSION", "", names(df_all))

However, this does not effect any change. Can you explain it? What should I do instead?

Your advice will be appreciated.

You can change the names with gsub but you must also save them back into the data.frame.

colnames(dfall) = gsub("PROFESSION", "", colnames(dfall))

You can't get rid of the dfall$ part. That is not really part of the column name, rather dfall$PROFESSIONEngineer specifies the PROFESSIONEngineer column of the dfall data.frame .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM