2009-08-25 76 views
0

假設我有一個N行data.frame。 id列有10個唯一值;所有這些值都是大於1e7的整數。我想將它們重命名爲1到10,並將這些新ID保存爲我的data.frame中的一列。重命名大ID

此外,我想容易地確定1)id給出id.new和2)給定的idid.new

例如:

> set.seed(123) 
> ids <- sample(1:1e7,10) 
> A <- data.frame(id=sample(ids,100,replace=TRUE), 
        x=rnorm(100)) 
> head(A) 
     id   x 
1 4566144 1.5164706 
2 9404670 -1.5487528 
3 5281052 0.5846137 
4 455565 0.1238542 
5 7883051 0.2159416 
6 5514346 0.3796395 

回答

1

嘗試這種情況:

A$id.new <- match(A$id,unique(A$id)) 

附加評論: 要獲得的值的表:

rbind(unique(A$id.new),unique(A$id)) 
+0

ooooh。沒有想到這一點。這很漂亮。有什麼方法可以輕鬆恢復映射嗎? – 2009-08-25 21:56:39

+0

只保存'獨特的(A $ id)' - 它相當於'levels(因子(A $ id))' – hadley 2009-08-25 22:04:06

1

使用因素:

> A$id <- as.factor(A$id) 
> A$id.new <- as.numeric(A$id) 
> head(A) 
     id   x id.new 
1 4566144 1.5164706  4 
2 9404670 -1.5487528  10 
3 5281052 0.5846137  5 
4 455565 0.1238542  1 
5 7883051 0.2159416  7 
6 5514346 0.3796395  6 

假定x是舊的標識,您希望新的一個。

> x <- 7883051 
> as.numeric(which(levels(A$id)==x)) 
[1] 7 

假設y是新ID並且您想要舊ID。

> as.numeric(as.character(A$id[which(as.integer(A$id)==y)[1]])) 
[1] 5281052 

(以上發現ID在這對於因子內部代碼是5是否有更好的方法的第一個值?)

+0

舊到新的不需要'作爲。 numeric'。 新到舊只是'水平(A $ id)[新]' – hadley 2009-08-25 22:02:56

0

一種選擇是使用hash包:

> library(hash) 
> sn <- sort(unique(A$id)) 
> g <- hash(1:length(sn),sn) 
> h <- hash(sn,1:length(sn)) 
> A$id.new <- .get(h,A$id) 
> head(A) 
     id   x id.new 
1 4566144 1.5164706  4 
2 9404670 -1.5487528  10 
3 5281052 0.5846137  5 
4 455565 0.1238542  1 
5 7883051 0.2159416  7 
6 5514346 0.3796395  6 

假設x是舊的ID,並且您想要新的ID。

> x <- 7883051 
> .get(h,as.character(x)) 
7883051 
     7 

假設y是新ID並且您想要舊ID。

> y <- 5 
> .get(g,as.character(y)) 
     5 
5281052 

(這有時可以比使用因子更方便/透明)

1

您可以使用facto R()/排序()在這裏:

R> set.seed(123) 
R> ids <- sample(1:1e7,10) 
R> A <- data.frame(id=sample(ids,100,replace=TRUE), x=rnorm(100)) 
R> A$id.new <- as.ordered(as.character(A$id)) 
R> table(A$id.new) 

2875776 4089769 455565 4566144 5281052 5514346 7883051 8830172 8924185 9404670 
     6  10  6  8  12  10  13  10  10  15 

然後你就可以使用as.numeric()映射到1至10:

R> A$id.new <- as.numeric(A$id.new) 
R> summary(A) 
     id    x    id.new  
Min. : 455565 Min. :-2.3092 Min. : 1.00 
1st Qu.:4566144 1st Qu.:-0.6933 1st Qu.: 4.00 
Median :5514346 Median :-0.0634 Median : 6.00 
Mean :6370243 Mean :-0.0594 Mean : 6.07 
3rd Qu.:8853675 3rd Qu.: 0.5575 3rd Qu.: 8.25 
Max. :9404670 Max. : 2.1873 Max. :10.00 
R>