我有一个矩阵并想重新排序行,以便例如第5行可以切换到第2行而第2行则转到第7行。我有一个列表,其中所有的rownames都以\n
和{I}分隔以为我可以以某种方式将其读入R(它是一个txt文件),然后只使用矩阵的名称(在我的情况下'k'并执行类似k[txt file,]-> k_new
的操作但这不起作用,因为标识符不是第一列,但被定义为rownames。
答案 0 :(得分: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