joon
joon

Reputation: 81

replacing specific elements of a vector

I am trying to make a user-defined function below using the R

wrkexpcode.into.month <- function(vec) {
  tmp.vec <- vec
  tmp.vec[tmp.vec == 0 | tmp.vec == 9] <- NA
  tmp.vec[tmp.vec == 1] <- 4
  tmp.vec[tmp.vec == 2] <- 13
  tmp.vec[tmp.vec == 3] <- 31
  tmp.vec[tmp.vec == 4] <- 78
  tmp.vec[tmp.vec == 5] <- 174
  tmp.vec[tmp.vec == 6] <- 240

  return (tmp.vec)
}

but when I execute with a simple command like

wrkexpcode.into.month(c(3,2,2,3,1,3,5,6,4))

the result comes like

[1]  31  13  13  31  78  31 174 240  78

but I expect the result like

[1]  31  13  13  31  **4**  31 174 240  78

How can I fix this?

Upvotes: 1

Views: 93

Answers (3)

altimit
altimit

Reputation: 421

You could create matrix pointing the input value (column1) to the desired output value (column2)

table=matrix(c(0,1,2,3,4,5,6,9,NA,4,13,31,78,174,240,NA),ncol=2) 

And using sapply on the vector c(3,2,2,3,1,3,5,6,4)

 sapply(c(3,2,2,3,1,3,5,6,4), function(x) table[which(table[,1] == x),2] )

to give you the desired output too

Upvotes: 0

Paul Hiemstra
Paul Hiemstra

Reputation: 60934

You have to carefully follow the flow of your function, evaluating what the values are. You are expecting 1 to be replaced by 4 based on tmp.vec[tmp.vec == 1] <- 4, however in tmp.vec[tmp.vec == 4] <- 78 later down the road, the 4 is replaced by a 78. This is caused by replacing the values in tmp.vec and using tmp.vec for determining what needs to be replaced. Like @MattewPlourde said, you need to base the replacement on vec:

tmp.vec[vec == 1] <- 4

Although I would simply replace the code by:

wrkexpcode.into.month <- function(vec) {
    translation_vector = c('0' = NA, '1' = 4, '2' = 13, '3' = 31, 
                           '4' = 78, '5' = 174, '6' = 240, '9' = NA)
    return(translation_vector[as.character(vec)])
}
wrkexpcode.into.month(c(3,2,2,3,1,3,5,6,4))
#   3   2   2   3   1   3   5   6   4 
#  31  13  13  31   4  31 174 240  78 

See also a blogpost I wrote recently about this kind of operation.

Upvotes: 3

Mark Heckmann
Mark Heckmann

Reputation: 11431

It think it will be much easier to use one of the many recode functions that are designed for such purposes instead of hard-coding it. It's just a one-liner then, e.g.

library(likert)
x <- c(3,2,2,3,1,3,5,6,4)

recode(x, from=c(0:6, 9), to=c(NA, 4,13,31,78,174,240,NA))
[1] 31  13  13  31   4  31 174 240  78

And if desired, wrap it into a function, e.g.

wrkexpcode.into.month <- function(x)
  recode(x, from=c(0:6, 9), to=c(NA, 4,13,31,78,174,240,NA))

wrkexpcode.into.month(x)
[1] 31  13  13  31   4  31 174 240  78 

Upvotes: 2

Related Questions