I would like to convert the values in a column of an existing data frame into row names. Is is possible to do this without exporting the data frame and then reimporting it with a row.names =
call?
我希望将现有数据帧的列中的值转换为行名称。是否可以不导出数据帧,然后使用row.names =调用重新导入数据帧?
For example I would like to convert:
例如,我想要转换:
> samp
names Var.1 Var.2 Var.3
1 A 1 5 0
2 B 2 4 1
3 C 3 3 2
4 D 4 2 3
5 E 5 1 4
into:
成:
> samp.with.rownames
Var.1 Var.2 Var.3
A 1 5 0
B 2 4 1
C 3 3 2
D 4 2 3
E 5 1 4
thanks
谢谢
4 个解决方案
#1
94
This should do:
这个应该做的是:
samp2 <- samp[,-1]
rownames(samp2) <- samp[,1]
So in short, no there is no alternative to reassigning.
所以简而言之,没有任何替代选择。
Edit: Correcting myself, one can also do it in place: assign rowname attributes, then remove column:
编辑:纠正自己,你也可以这样做:分配rowname属性,然后删除列:
R> df<-data.frame(a=letters[1:10], b=1:10, c=LETTERS[1:10])
R> rownames(df) <- df[,1]
R> df[,1] <- NULL
R> df
b c
a 1 A
b 2 B
c 3 C
d 4 D
e 5 E
f 6 F
g 7 G
h 8 H
i 9 I
j 10 J
R>
#2
18
in one line
在一行
> samp.with.rownames <- data.frame(samp[,-1], row.names=samp[,1])
#3
11
As of 2016 you can also use the tidyverse
.
到2016年,你也可以使用tidyverse。
library(tidyverse)
samp %>% remove_rownames %>% column_to_rownames(var="names")
#4
2
You can execute this in 2 simple statements:
你可以用两个简单的语句来执行:
row.names(samp) <- samp$names
samp[1] <- NULL
#1
94
This should do:
这个应该做的是:
samp2 <- samp[,-1]
rownames(samp2) <- samp[,1]
So in short, no there is no alternative to reassigning.
所以简而言之,没有任何替代选择。
Edit: Correcting myself, one can also do it in place: assign rowname attributes, then remove column:
编辑:纠正自己,你也可以这样做:分配rowname属性,然后删除列:
R> df<-data.frame(a=letters[1:10], b=1:10, c=LETTERS[1:10])
R> rownames(df) <- df[,1]
R> df[,1] <- NULL
R> df
b c
a 1 A
b 2 B
c 3 C
d 4 D
e 5 E
f 6 F
g 7 G
h 8 H
i 9 I
j 10 J
R>
#2
18
in one line
在一行
> samp.with.rownames <- data.frame(samp[,-1], row.names=samp[,1])
#3
11
As of 2016 you can also use the tidyverse
.
到2016年,你也可以使用tidyverse。
library(tidyverse)
samp %>% remove_rownames %>% column_to_rownames(var="names")
#4
2
You can execute this in 2 simple statements:
你可以用两个简单的语句来执行:
row.names(samp) <- samp$names
samp[1] <- NULL