Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a quick way to replace column values in R?

Tags:

r

Suppose we have a data frame containing numeric values which looks like:

Temperature Height
32          157
31          159
33          139

I want to replace Height values with pic_00001, pic_00002 etc. so that the end result is:

Temperature Height
32          pic_00001
31          pic_00002
33          pic_00003

There are 10,000+ rows in the full data frame, hence I need a quicker way than doing this manually.

like image 506
HelpMePlease Avatar asked Dec 05 '25 04:12

HelpMePlease


1 Answers

You can use sprintf:

# create the example used by the OP
dat <- data.frame(Temperature = 31:33, 
                  Height = c(157, 159, 139))

# use sprintf along with seq_len
dat$Height <- sprintf("pic_%05d", seq_len(NROW(dat)))

# show the result
dat
#R>  Temperature    Height
#R> 1          31 pic_00001
#R> 2          32 pic_00002
#R> 3          33 pic_00003

You can change the 05d if you want more leading zeros. E.g. 07d will give a seven digit sequence. The manual page for sprintf have further details.

like image 114
Benjamin Christoffersen Avatar answered Dec 07 '25 19:12

Benjamin Christoffersen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!