繁体   English   中英

在R中更改字符矩阵列名称和data.frame会话

[英]Change character matrix column names and data.frame converstion in R

H,

我在R中有一个100x5字符矩阵,第一行包含列名,如何将第一行移动为列标题/名称,以及如何将其转换为数据框?

谢谢

字符矩阵的子集:

     [,1]           [,2]           [,3]           [,4]           [,5]          
V1   "I6839"        "I6844"        "I6850"        "I6875"        "I6906"
V2   "53"           "67"           "39"           "42"           "36"          
V3   "53"           "60"           "47"           "44"           "36"          
V4   "59"           "59"           "47"           "47"           "36"          
V5   "61"           "56"           "40"           "45"           "34"   

所需的输出:

     [I6839]        [I6844]        [I6850]        [I6875]        [I6906]          
V1   "53"           "67"           "39"           "42"           "36"          
V2   "53"           "60"           "47"           "44"           "36"          
V3   "59"           "59"           "47"           "47"           "36"          
V4   "61"           "56"           "40"           "45"           "34"   

这是一个非常简单的更改。

假设我们从这里开始:

m <- matrix(c("a", "b", "c", 1, 2, 3, 4, 5, 6), 
            nrow = 3, byrow = TRUE, 
            dimnames = list(c("A", "B", "C"), NULL))
m
#   [,1] [,2] [,3]
# A "a"  "b"  "c" 
# B "1"  "2"  "3" 
# C "4"  "5"  "6"

如果需要matrix ,请尝试:

n <- m[-1, ]
colnames(n) <- m[1, ]
n
#   a   b   c  
# B "1" "2" "3"
# C "4" "5" "6"

如果您需要data.frame ,请尝试:

setNames(data.frame(m[-1, ], stringsAsFactors = FALSE), m[1, ])
#   a b c
# B 1 2 3
# C 4 5 6

请注意,由于我们使用stringsAsFactors = FALSE ,因此这些值将保留为字符。

str(.Last.value)
# 'data.frame':  2 obs. of  3 variables:
#  $ a: chr  "1" "4"
#  $ b: chr  "2" "5"
#  $ c: chr  "3" "6"
mat2 <- structure(c("I6839", "53", "53", "59", "61", "I6844", "67", "60", 
"59", "56", "I6850", "39", "47", "47", "40", "I6875", "42", "44", 
"47", "45", "I6906", "36", "36", "36", "34"), .Dim = c(5L, 5L
), .Dimnames = list(c("V1", "V2", "V3", "V4", "V5"), NULL))




 res <-  matrix(mat2[-1,], nrow=4,
   dimnames=list(rownames(mat2)[1:4], paste0("[", mat2[1,],"]")))
res 
#   [I6839] [I6844] [I6850] [I6875] [I6906]
#V1 "53"    "67"    "39"    "42"    "36"   
#V2 "53"    "60"    "47"    "44"    "36"   
#V3 "59"    "59"    "47"    "47"    "36"   
#V4 "61"    "56"    "40"    "45"    "34"   

as.data.frame(res, stringsAsFactors=F) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM