Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dataframe

r

gsub

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

"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.

like image 895
ak7 Avatar asked Dec 19 '22 08:12

ak7


1 Answers

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 .

like image 59
G5W Avatar answered Dec 29 '22 00:12

G5W