题
假设我有具有N行一个data.frame。该id
列具有10点唯一的值;所有这些值都超过整数更大1E7。我想重命名它们被编号为1到10,并保存这些新的ID作为列在我data.frame。
此外,我想容易地确定1)id
给出id.new
和2)给定的id.new
id
。
例如:
> 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
解决方案
尝试这种情况:
A$id.new <- match(A$id,unique(A$id))
其他评论:强> 要获得的值的表:
rbind(unique(A$id.new),unique(A$id))
其他提示
使用因素:
> 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和你想要的旧的。
> as.numeric(as.character(A$id[which(as.integer(A$id)==y)[1]]))
[1] 5281052
(以上发现ID在这对于因子内部代码是5是否有更好的方法的第一个值?)
您可以使用系数()/排序()在这里:
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>
一种选择是使用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是旧的标识,您希望新的一个。
> x <- 7883051
> .get(h,as.character(x))
7883051
7
假设y是新的ID和你想要的旧的。
> y <- 5
> .get(g,as.character(y))
5
5281052
(这有时可能是更方便的/比使用因子是透明的。)
不隶属于 StackOverflow