如何替换 data.frame 中的列值?

How do I replace column values in data.frame?

我有两个data.frame。

d <- data.frame(a=letters[1:5], b=c(1:5))
  a b
1 a 1
2 b 2
3 c 3
4 d 4
5 e 5

t <- data.frame(old=c('a','c','d'), new=c('aa','cc','dd'))
  old new
1   a  aa
2   c  cc
3   d  dd

我想像下面这样替换。

  a b
1 aa 1
2 b  2
3 cc 3
4 dd 4
5 e  5

我想使用应用功能。 我该怎么办?

我们可以使用来自 data.table 的连接。我们将 'data.frame' 转换为 'data.table' (setDT(d)) 并在第一列上与 't' 连接,将 'a' 列与 'new' 替换 'd' 数据集中 'a' 中的值。

library(data.table)#v1.9.6+
setDT(d)[t, a:= new, on=c('a'='old')][]
d
#    a b
#1: aa 1
#2:  b 2
#3: cc 3
#4: dd 4
#5:  e 5

因为你有因素:

levels(d$a)[match(t$old, levels(d$a))] <- as.character(t$new)
#   a b
#1 aa 1
#2  b 2
#3 cc 3
#4 dd 4
#5  e 5

如果您的 t$old 之一不在 d$a 中,这将出错。

使用 mergeifelse

df <- merge(d, t, all.x = T, by.x = "a", by.y = "old")
df$a <- ifelse(is.na(df$new), as.character(df$a), as.character(df$new))
#Removing the "new" column
df <- df[, -3]

#a b
#1 aa 1
#2  b 2
#3 cc 3
#4 dd 4
#5  e 5