0

I have a dataset,prgeng. 7 columns, 1 of it is educ.

I want to replace the values of educ with other values. I need to replace values 1:9 with 1, 10:12 with 2, 13 with 3 and so on.

It doesnt work using the : operator.

prgeng <- load(url('https://github.com/matloff/fasteR/blob/master/data/prgeng.RData?raw=true'))
educ <- prgeng$educ

educ[educ == 1:9] <- 1 # doesnt work
# Warning: longer object length is not a multiple of shorter object lengthWarning: longer object length is not a multiple of shorter object length

educ[educ == 1] <- 1 # works

I think its weird because this on the other hand works.

t1 <- 1:2500
t1[t1 == 1:1000] <- 1 # this works 

I get that the warning is key but i cannot get my head around what its supposed to mean. And other examples here are based on slightly different cases. I dont think it happens because educ is a factor because:

  1. i converted educ to a vector and it changed nothing
  2. Im able to change the values one by one
notRelevant
  • 43
  • 2
  • 7
  • 4
    Try `educ[educ %in% 1:9] <- 1`. `==` is elementwise operator. So, it recycles if the length of the rhs is less than the one on the lhs. If it is not a multiple, then it shows the warning – akrun May 01 '23 at 17:50
  • Agreed, see https://stackoverflow.com/q/15358006/3358272, https://stackoverflow.com/q/42637099/3358272 – r2evans May 01 '23 at 18:20
  • 1
    @akrun that was it. Thank you!! could you post it as an answer so i can close this issue? – notRelevant May 01 '23 at 18:30

1 Answers1

2

We could use %in% instead of == as == is elementwise operator

educ[educ %in% 1:9] <- 1
akrun
  • 874,273
  • 37
  • 540
  • 662