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

Viewed 236

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.

4 Answers

You can do:

id <- seq_len(nrow(data))
new_values <- paste("pic_",id,sep = "")

data$Height <- new_values

You can also use the following solution:

library(dplyr)
library(stringr)

df %>%
  mutate(across(Height, ~ str_c("pic_", str_pad(row_number(), 5, "left", "0"))))

  Temperature    Height
1          32 pic_00001
2          31 pic_00002
3          33 pic_00003

to achieve final output (from original by monjeanjean, i cant comment yet lol):

id <- seq_len(nrow(data))
new_values <- paste("pic_",formatC(x,width=5,flag="0",format="fg"),sep = "")

data$Height <- new_values

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.

Related