在R编程中,订单是否总是被保持和尊重?

huangapple go评论78阅读模式
英文:

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

问题

我理解的是,当我有一个包含10行的矩阵或数据框时,如果它是新创建的,行名称会从1到10。我想确保,如果我输入一个具有给定名称的向量(如:c("Jhon", "Molly", ... "Lucy")),它将按照我考虑的顺序严格应用(1被替换为"Jhon",一直到10被替换为"Lucy"),还是它会随机地用向量中的任何名称替换每一行?

英文:

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?

答案1

得分: 0

v1[numvec]


如果我们使用 row.names 来替换数值,请确保将其更改为 numeric,使用 as.numeric,否则它将是一个 character 类型,进行不同的匹配

数据

v1 <- c("Jhon", "Molly", "Jolly", "Holy", "Loly", "Solly", "Tolly",
          "Dolly", "Hally", "Lucy")
set.seed(24)
numvec <- sample(10, 50, replace = TRUE)
英文:

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)

huangapple
  • 本文由 发表于 2020年1月7日 01:33:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/59616509.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定