簡體   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