一意の ID を持つ列を作成する必要があります。基本的には、行番号を独自の列として追加します。現在のデータ フレームは次のようになります。
V1 V2
1 23 45
2 45 45
3 56 67
次のように表示する方法:
V1 V2 V3
1 23 45
2 45 45
3 56 67
?
どうもありがとう
2 つのtidyverseの代替 (sgibb のサンプル データを使用):
tibble::rowid_to_column(d, "ID")
与える:
ID V1 V2 1 1 23 45 2 2 45 45 3 3 56 67
または:
dplyr::mutate(d, ID = row_number())
与える:
V1 V2 ID 1 23 45 1 2 45 45 2 3 56 67 3
ご覧のとおり、 -function は新しい列rowid_to_column
を他の列の前に追加し、mutate
& row_number()
-combo は新しい列を他の列の後に追加します。
そして、別のベース R 代替:
d$ID <- seq_along(d[,1])
使用できますcbind
:
d <- data.frame(V1=c(23, 45, 56), V2=c(45, 45, 67))
## enter id here, you could also use 1:nrow(d) instead of rownames
id <- rownames(d)
d <- cbind(id=id, d)
## set colnames to OP's wishes
colnames(d) <- paste0("V", 1:ncol(d))
編集: @dacko の提案の比較です。d$id <- seq_len(nrow(d)
はわずかに高速ですが、列の順序が異なります (id
は最後の列です。並べ替えは を使用するよりも遅いようですcbind
):
library("microbenchmark")
set.seed(1)
d <- data.frame(V1=rnorm(1e6), V2=rnorm(1e6))
cbindSeqLen <- function(x) {
return(cbind(id=seq_len(nrow(x)), x))
}
dickoa <- function(x) {
x$id <- seq_len(nrow(x))
return(x)
}
dickoaReorder <- function(x) {
x$id <- seq_len(nrow(x))
nc <- ncol(x)
x <- x[, c(nc, 1:(nc-1))]
return(x)
}
microbenchmark(cbindSeqLen(d), dickoa(d), dickoaReorder(d), times=100)
# Unit: milliseconds
# expr min lq median uq max neval
# cbindSeqLen(d) 23.00683 38.54196 40.24093 42.60020 47.73816 100
# dickoa(d) 10.70718 36.12495 37.58526 40.22163 72.92796 100
# dickoaReorder(d) 19.25399 68.46162 72.45006 76.51468 88.99620 100
次を使用してこれを行うこともできますdplyr
。
DF <- mutate(DF, id = rownames(DF))
関数rownames_to_column()
は行名を列に移動します。tidyverse
パッケージ ( docs )にあります。
rownames_to_column(DF, "my_column_name")
column_to_rownames()
逆の操作に使用します。