0

I have a column that contains multiple 13's, 14's, 15's..all the way to 24. I would like to replace each value, with the same interval of 1, but start with 1 and go to 12 (so 13 = 1, 14 = 2, and so on).

I tried using the apply function and ifelse statement to see if the condition is met, change to new value but I was not successful.

Any help would be greatly appreciated!

2
  • 2
    x - min(x) + 1 Commented Dec 3, 2019 at 21:55
  • wouldn't just subtracting 12 from the current values return what you need ? x - 12 Commented Dec 4, 2019 at 0:35

1 Answer 1

1

An option is match to match to the value with the unique values assuming the column is ordered

match(df1$col, unique(df1$col)) 

match returns the position index of the matching 'x' vector with the table values i.e the unique elements i.e.

match(c(12, 14, 12, 14), c(12, 14)) #[1] 1 2 1 2 

Or with factor which can be coerced to integer to return the integer storage values of the factor, which would be starting from 1.

as.integer(factor(df1$col)) 

data

df1 <- data.frame(col = rep(13:24, each = 3)) 
Sign up to request clarification or add additional context in comments.

7 Comments

@Dinho You can do this directly in factor i.e. factor(df1$col, levels = 13:24, labels = c(month.abb[10:12], month.abb[1:9]))
Absolutely brilliant - cheers man. Commenting now but makes sense what you did!
@Dinho v1 <- sample(13:24, 20, replace = TRUE); factor(v1, levels = 13:24, labels = c(month.abb[10:12], month.abb[1:9]))# [1] Nov Apr Aug Jun Feb Aug Jan Jan Jul May Mar Sep Oct Dec Nov Feb Jun Jan Jul Jan Levels: Oct Nov Dec Jan Feb Mar Apr May Jun Jul Aug Sep
@Dinho It can become NAs if the values in the column is not 13:24 or if it is character i.e. it should match the levels we are entering in factor
I didn't realize the values werent 13:24 -__- worked like a charm. apprecaite the help man. and the explanation.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.