Search code examples
rstructure

Is the order always kept and respected when programming in R?


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?


Solution

  • 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)