英文:
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 <- 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 <- 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论