保留矩阵列和行标题,同时将字符转换为数字

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

Preserve matrix column & row titles while converting character to numeric

问题

我有一个矩阵,最近对其进行了转置,将数值数字转换为字符数字:

所以,我使用as.numeric将单元格转换回数值,如下所示:

  1. cyc_daily_v5 <- matrix(as.numeric(cyc_daily_v4), ncol=ncol(cyc_daily_v4))

然而,这也转换了我的列和行标题:

是否有一种方法可以在字符转数字的过程中保留原始的星期几列标题?

英文:

I have a matrix that I recently transposed that converted the numeric numbers into character numbers:

保留矩阵列和行标题,同时将字符转换为数字
保留矩阵列和行标题,同时将字符转换为数字

So, I used as.numeric to convert the cells back to numeric like such:

  1. cyc_daily_v5 &lt;- matrix(as.numeric(cyc_daily_v4), ncol=ncol(cyc_daily_v4))

However, this converted my column & row title headings as well:

保留矩阵列和行标题,同时将字符转换为数字

Is there a way I can retain the original day of the week column titles during the character-to-numeric conversion?

答案1

得分: 0

将行和列的名称转移到您新创建的数据框中。如果成功了,请随时告诉我。

  1. cnames = colnames(cyc_daily_v4)
  2. rnames = rownames(cyc_daily_v4)
  3. cyc_daily_v5 = as.data.frame(cyc_daily_v5)
  4. rownames(cyc_daily_v5) = rnames
  5. colnames(cyc_daily_v5) = cnames
英文:

Transfer the row and column names into your newly created data frame. Feel free to let me know if it worked.

  1. cnames = colnames(cyc_daily_v4)
  2. rnames = rownames(cyc_daily_v4)
  3. cyc_daily_v5 = as.data.frame(cyc_daily_v5)
  4. rownames(cyc_daily_v5) = rnames
  5. colnames(cyc_daily_v5) = cnames

答案2

得分: 0

你可以使用 storage.mode()

  1. test_mat <- matrix(c("1", "2", "4", "5", "6", "7"), ncol = 2)
  2. dimnames(test_mat) <- list(c("a", "b", "c"), c("AA", "BB"))
  3. test_mat
  4. # AA BB
  5. # a "1" "5"
  6. # b "2" "6"
  7. # c "4" "7"
  8. storage.mode(test_mat) <- "numeric"
  9. test_mat
  10. # AA BB
  11. # a 1 5
  12. # b 2 6
  13. # c 4 7
英文:

You can use storage.mode():

  1. test_mat &lt;- matrix(c(&quot;1&quot;, &quot;2&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;), ncol = 2)
  2. dimnames(test_mat) &lt;- list(c(&quot;a&quot;, &quot;b&quot;, c&quot;), c(&quot;AA&quot;, &quot;BB&quot;))
  3. test_mat
  4. # AA BB
  5. # a &quot;1&quot; &quot;5&quot;
  6. # b &quot;2&quot; &quot;6&quot;
  7. # c &quot;4&quot; &quot;7&quot;
  8. storage.mode(test_mat) &lt;- &quot;numeric&quot;
  9. test_mat
  10. # AA BB
  11. # a 1 5
  12. # b 2 6
  13. # c 4 7

huangapple
  • 本文由 发表于 2023年5月30日 11:27:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76361442.html
匿名

发表评论

匿名网友

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

确定