在r中逐行改变数据的顺序和名称

时间:2015-08-30 22:03:52

标签: r dataframe

我有一个数据框,如下所示:

> DisintegrationBehavior
             gden    degree
1.txt  0.45000000 0.7083333
14.txt 0.58333333 0.5000000
11.txt 0.50000000 0.4166667
12.txt 0.50000000 0.6666667
13.txt 0.25000000 0.5000000

我想从行名中删除.txt,然后添加" team"在每个行号前面,然后按行号(或更简单的顺序)对结果进行排序,以便最终结果如下:

> DisintegrationBehavior
             gden    degree
team1  0.45000000 0.7083333
team11 0.50000000 0.4166667
team12 0.50000000 0.6666667
team13 0.25000000 0.5000000
team14 0.58333333 0.5000000

谢谢!

1 个答案:

答案 0 :(得分:1)

你可以做到

s <- sub(".txt", "", rownames(df), fixed = TRUE)
rownames(df) <- paste0("team", s)
df[order(as.numeric(s)), ]
#             gden    degree
# team1  0.4500000 0.7083333
# team11 0.5000000 0.4166667
# team12 0.5000000 0.6666667
# team13 0.2500000 0.5000000
# team14 0.5833333 0.5000000

数据:

df <- structure(list(gden = c(0.45, 0.58333333, 0.5, 0.5, 0.25), degree = c(0.7083333, 
0.5, 0.4166667, 0.6666667, 0.5)), .Names = c("gden", "degree"
), class = "data.frame", row.names = c("1.txt", "14.txt", "11.txt", 
"12.txt", "13.txt"))