1

I have a variable in a data frame which consists of either 5 or 6 digits/characters. Those values in the variable with 5 digits are all numbers e.g. 27701 those with 6 digits however all have a character 'C' preceding the numbers e.g. C22701.

How can I replace the 'C' characters with 999 for example?

I have tried:

replace(data$varname,'C',999) 

Any ideas folks?

2
  • 5
    data$varname <- gsub('C', '999', data$varname) maybe? If varname is a factor, it could cause problems though Commented Sep 2, 2014 at 12:12
  • What format do you want the variable in the end? Character? Factor? Numeric? Commented Sep 2, 2014 at 13:13

2 Answers 2

2

data$varname <- as.numeric(gsub('C', '999', data$varname)) should do the trick, I think. Assuming you want a numeric vector in the end. If you want a character vector, then you can leave as.numeric off.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use a substring to remove the first letter, and paste0 to add 999 to it.

> x <- c("C000", "P1745") > paste0("999", substring(x,2)) # [1] "999000" "9991745" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.