0

What I mean is that when I have a matrix or data frame with 10 rows, if it's newly created row names go from 1 to 10. I want to make sure that if I type a vector with given names (like: c("Jhon","Molly",..."Lucy") it is going to be applied strictly in order as I think about it (1 being replaced by "Jhon" until 10 is replaced by "Lucy") or it could randomly replace each row with any name on my vector?

MelaniaCB
  • 427
  • 5
  • 16
  • 2
    Can you post the code you're using along with a reproducible example of input data? Are you referring to this operation `rownames(mat) <- char_vec`? – IceCreamToucan Jan 06 '20 at 17:38
  • 2
    How exactly are you doing the replacement? It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. R rarely ever changes the order of user input on it's own. – MrFlick Jan 06 '20 at 17:38
  • I could, but I am not using any code. I just want to know that if I got a matrix-data frame-anything like this, with 10 rows and I just type c(" ", ...) with 10 names inside, is it going to be applied strictly in order if I used `rownames( )` or `colnames( )` ?? – MelaniaCB Jan 06 '20 at 17:49
  • @IceCreamToucan. Exactly, that's what I mean, would they ever change order or they'll always be replaced one by one in the same order? – MelaniaCB Jan 06 '20 at 17:55
  • 2
    Yes, the order will be preserved (generally), but you should also know about recycling too... if the lengths are not equal, in many cases the shorter vector will be "recycled" (start at the beginning again and repeated) until it gets to the length of the longer vector, often with a warning. See, e.g., `cbind(c("a", "b"), c("d", "e", "f"))` – Gregor Thomas Jan 06 '20 at 18:05
  • What do you mean that you're not using any code? Isn't this a question about code? – camille Jan 06 '20 at 18:32
  • Yes indeed, @camille, but it didn't came up because I was programming something in particular, just thought about it and asked because is nice to have that thing clear for future reference. – MelaniaCB Jan 06 '20 at 19:33

1 Answers1

0

We can use the numbers as index

v1[numvec]

If we use row.names to replace value, make sure to change it to numeric with as.numeric or else it is a character class and would do a different matching

data

v1 <- c("Jhon", "Molly", "Jolly", "Holy", "Loly", "Solly", "Tolly",
          "Dolly", "Hally", "Lucy")
set.seed(24)
numvec <- sample(10, 50, replace = TRUE)
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662