2012-08-30 119 views
0

我有一个矩阵,并想重新排序行,例如第5行可以切换到第2行和第2行说对第7行。我有一个名单与所有rownames分隔\n,我想我可以以某种方式将它读入R(它的一个txt文件),然后只是使用矩阵的名称(在我的情况'K'和做一些像k[txt file,]-> k_new但这不起作用,因为标识符不是第一个列,但被定义为rownames如何重新排列矩阵行

+0

你说标题中的列,但文本中的行。这是什么? –

+2

发布dput(k)的输出应该有助于澄清你的问题中的一些突出的含糊之处。 –

回答

1
k[ c(1,5,3,4,7,6,2), ] #But probably not what you meant.... 

或许(如果你的“K”对象rownames比默认的字符数字序列以外的东西)。

k[ char_vec , ] # where char_vec will get matched to the row names. 

(dat <- structure(list(person = c(1, 1, 1, 1, 2, 2, 2, 2), time = c(1, 
2, 3, 4, 1, 2, 3, 4), income = c(100, 120, 150, 200, 90, 100, 
120, 150), disruption = c(0, 0, 0, 1, 0, 1, 1, 0)), .Names = c("person", 
"time", "income", "disruption"), row.names = c("h", "g", "f", 
"e", "d", "c", "b", "a"), class = "data.frame")) 

dat[ c('h', 'f', 'd', 'b') , ] 
#------------- 
    person time income disruption 
h  1 1 100   0 
f  1 3 150   0 
d  2 1  90   0 
b  2 3 120   1 
+0

hallo - 我指的是行 - 所以如果我有一个正确的序列rownames名单,我可以只使用 k [txt文件,]? –

+0

我演示了如何重新排列行。 “[”引用rownames的“i”位置中的字符向量。 (我会纠正我的第二个误导选项,因为“txt”和“file”之间有一个空格,所以显然不能使用'k [txt file,]',但是如果你的对象被命名为“txtfile” k [txtfile,]' –