更改R中的字符矩阵列名称和data.frame转换

时间:2014-08-09 13:54:07

标签: r matrix character

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"   

2 个答案:

答案 0 :(得分:4)

这是一个非常直接的改变。

假设我们从这开始:

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"

答案 1 :(得分:0)

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)