【发布时间】:2018-02-01 14:55:35
【问题描述】:
我想在数据框的所有列中替换一组值。我提供了一种方法来做到这一点,但是,我怀疑不使用for 可能会有更好的方法。
table1<-read.table(text="
col1 col2 col3
C02 M36 MC0237
C03 C02 M44
C04 M48 F04
F04 M61 M59
F05 M64 M65" , header=TRUE, stringsAsFactors=FALSE)
table2<-read.table(text="
orig subst
C02 36
C04 48
D02 24
D04 51
F04 61" , header=TRUE, stringsAsFactors=FALSE)
table2#<-table2[,c(1,2)]
mylist <- as.character(table2$subst)
names(mylist) <- table2$orig
for (i in 1:length(mylist)){
table1[which(table1==names(mylist)[i],arr.ind = T)]<-mylist[i]
}
# table1 GOAL, with values substituted in all columns based on table2
# col1 col2 col3
# 1 36 M36 MC0237 # EDITED ABOVE
# 2 C03 36 M44
# 3 48 M48 61
# 4 61 M61 M59
# 5 F05 M64 M65
【问题讨论】:
标签: r dataframe replace lapply substitution