【问题标题】:Substitute values in all columns of dataframe based in other dataframe基于其他数据框替换数据框所有列中的值
【发布时间】: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


    【解决方案1】:

    这是一个单一的班轮,

    table1[] <- lapply(table1, function(i) ifelse(grepl(paste(table2$orig, collapse = '|'), i), 
                                                      table2$subst[match(i, table2$orig)], i))
    

    给了

      col1 col2 col3
    1   36  M36  M37
    2  C03   36  M44
    3   48  M48   61
    4   61  M61  M59
    5  F05  M64  M65
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多