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

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

Preserve matrix column & row titles while converting character to numeric

问题

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

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

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:

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

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

cnames = colnames(cyc_daily_v4)
rnames = rownames(cyc_daily_v4)
cyc_daily_v5 = as.data.frame(cyc_daily_v5)
rownames(cyc_daily_v5) = rnames
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.

cnames = colnames(cyc_daily_v4)
rnames = rownames(cyc_daily_v4)
cyc_daily_v5 = as.data.frame(cyc_daily_v5)
rownames(cyc_daily_v5) = rnames
colnames(cyc_daily_v5) = cnames

答案2

得分: 0

你可以使用 storage.mode()

test_mat <- matrix(c("1", "2", "4", "5", "6", "7"), ncol = 2)
dimnames(test_mat) <- list(c("a", "b", "c"), c("AA", "BB"))

test_mat
#   AA  BB 
# a "1" "5"
# b "2" "6"
# c "4" "7"

storage.mode(test_mat) <- "numeric"
test_mat
#   AA BB
# a  1  5
# b  2  6
# c  4  7
英文:

You can use storage.mode():

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)
dimnames(test_mat) &lt;- list(c(&quot;a&quot;, &quot;b&quot;, c&quot;), c(&quot;AA&quot;, &quot;BB&quot;))

test_mat
#   AA  BB 
# a &quot;1&quot; &quot;5&quot;
# b &quot;2&quot; &quot;6&quot;
# c &quot;4&quot; &quot;7&quot;

storage.mode(test_mat) &lt;- &quot;numeric&quot;
test_mat
#   AA BB
# a  1  5
# b  2  6
# 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:

确定