用另一个索引值替换数据集值 r

replace dataset values r by another indexed values

我有以下数据集

head(data)

  from  to
1    1   2
2    2   3
3    2  17
4    3   4
5    4   5
6    4 855

我有这个数据集

 > head(names)
           V1
1    Greenock
2     Glasgow
3     Preston
4  Birmingham
5 Southampton
6          Le

现在我想要的很简单:

head(data)

         from            to
1    Greenock     Glasgow
2    Glasgow      Preston
3    Glasgow      17 (you got the point)
4    Preston      Birmingham
5    Birmingham   Southampton
6    Birmingham   855

我尝试了这种老式的 for 循环,但是

> for(i in 1:nrow(data)){
+ data$from[i] <- names$V1[data$from]
+ data$to[i] <- names$V1[data$to]
+ }
  1. 效果不佳
  2. 我知道这不是很好的工作

有什么想法吗?

这是一种方法,使用一些逻辑子集和 replace()

dlg <- data <= nrow(names)
replace(data, dlg, as.character(names$V1)[unlist(data)][dlg])
#         from          to
# 1   Greenock     Glasgow
# 2    Glasgow     Preston
# 3    Glasgow          17
# 4    Preston  Birmingham
# 5 Birmingham Southampton
# 6 Birmingham         855

顺便说一句,datanames 都是重要基函数的名称,因此您可能需要重命名您的数据集。

R 的 factors 是为此类数据制作的。它将数据保存为数字,但添加了人类可读的 levels.

我只是将 fromto 列转换为 factors:

data$from <- factor(data$from)
data$to <- factor(data$to)

然后更改级别的标签:

levels(data$from) <- names$V1
levels(data$to) <- names$V1

以上代码对我有用:

data <- data.frame(
 from = 1:10,
 to = seq(from=10, to=1, by=-1))

names <- data.frame(
  V1 = c('a','b','c','d','e', 'f','g','h','i','j'))

data$from <- factor(data$from)
data$to <- factor(data$to)

levels(data$from) <- names$V1
levels(data$to) <- names$V1

print(data)

结果:

   from to
1     a  j
2     b  i
3     c  h
4     d  g
5     e  f
6     f  e
7     g  d
8     h  c
9     i  b
10    j  a

此答案确实假定您为每个数字都有一个标签。如果不是这种情况,则通常意味着数据有问题并且您希望抛出错误。您应该使用 Hadley 的 assertthat 包中的 stopifnot 或(更好)assert_that 断言 max(data[,c('to','from')]) <= nrow(names)(未测试)。

如果你不想做这个假设,你应该使用@RichardScriven 的回答。