Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201919

Changing multiple variables names following a specific pattern

$
0
0

I have a dataset with hundred of variables that looks roughly like this

dt <- data.frame(id= c(1,1,1,2,2,2,3,3,3), time=c(1,2,1,2,1,2,1,2,1), dp_eu_ = rnorm(9), EU_top = rnorm(9), fr_dp_us_ = rnorm(9), us = rnorm(9), c= rnorm(9), dp_eu_fit= rnorm(9))
dt
# id time     dp_eu_      EU_top      dp_us_          us            c  dp_eu_fit
# 1  1    1 -1.1184009 -1.07430118  0.61398523 -0.68343624 -0.050577369  0.2849573
# 2  1    2  0.4347047 -0.53454071 -0.30716538 -1.02328242  0.626537910  0.7790181
# 3  1    1  0.2318315 -0.05854228  0.05169733 -0.22130149 -0.224553878  1.5612293
# 4  2    2  1.2640080  2.07899296 -0.95918953 -0.35961156  0.839223862  0.5001897
# 5  2    1 -0.4374764 -0.25284854 -0.46251901  0.08630344  1.749488237  0.7155184
# 6  2    2  0.5042690  0.13322671  1.00881113  0.43807458 -0.007357072  0.5086272
# 7  3    1  0.3672216  1.92995242  0.48708183  0.58206127  0.112447259 -0.4707959
# 8  3    2 -1.5431709  0.53362731  1.17361087 -1.00932195 -0.125171990  0.8641184
# 9  3    1 -1.4577268  0.23413541 -0.32399489 -0.91040641  1.995611848  1.3348043

I would like to change the name of my variables with the following criteria: if the name of the variable name contains dp_ then eu and us should be in capital letters, EU and US respectively. Otherwise the name should remain the same

I know ho to change variable names one by one, but given that I have hundred of variables this operation should be systematized.

The final dataset should look something like this

f.dt <- data.frame(id= c(1,1,1,2,2,2,3,3,3), time=c(1,2,1,2,1,2,1,2,1), dp_EU_ = rnorm(9), EU_top = rnorm(9), fr_dp_US_ = rnorm(9), us = rnorm(9), c= rnorm(9), dp_EU_fit= rnorm(9))
f.dt
# id time     dp_EU_      EU_top      fr_dp_US_     us            c      dp_EU_fit
# 1  1    1 -1.1184009 -1.07430118  0.61398523 -0.68343624 -0.050577369  0.2849573
# 2  1    2  0.4347047 -0.53454071 -0.30716538 -1.02328242  0.626537910  0.7790181
# 3  1    1  0.2318315 -0.05854228  0.05169733 -0.22130149 -0.224553878  1.5612293
# 4  2    2  1.2640080  2.07899296 -0.95918953 -0.35961156  0.839223862  0.5001897
# 5  2    1 -0.4374764 -0.25284854 -0.46251901  0.08630344  1.749488237  0.7155184
# 6  2    2  0.5042690  0.13322671  1.00881113  0.43807458 -0.007357072  0.5086272
# 7  3    1  0.3672216  1.92995242  0.48708183  0.58206127  0.112447259 -0.4707959
# 8  3    2 -1.5431709  0.53362731  1.17361087 -1.00932195 -0.125171990  0.8641184
# 9  3    1 -1.4577268  0.23413541 -0.32399489 -0.91040641  1.995611848  1.3348043

Thanks a lot in advance for your help

Best regards


Viewing all articles
Browse latest Browse all 201919

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>