[英]How do I replace column values in data.frame?
I have two 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
And I want to replace like below. 我想替换如下。
a b
1 aa 1
2 b 2
3 cc 3
4 dd 4
5 e 5
I'd like to use apply function. 我想使用套用功能。 How should I do? 我应该怎么做?
We can use join from data.table
. 我们可以使用data.table
。 We convert the 'data.frame' to 'data.table' ( setDT(d)
) and join with 't' `on' the the first column, assign the 'a' column with the 'new' to replace the values in 'a' from 'd' dataset. 我们将'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
Since you have factors: 由于您有以下因素:
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
This will give an error if one of your t$old
is not in d$a
. 如果您的t$old
一个不在d$a
则会产生错误。
Used merge
along with ifelse
与ifelse
一起使用merge
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.