Replace value in column with corresponding value from another column in same dataframe

前端 未结 2 614
伪装坚强ぢ
伪装坚强ぢ 2021-01-15 08:42

Im trying to match a specific value in one column and replace it with the corresponding value from another column (same row). This is probably very easy... I have been tryin

相关标签:
2条回答
  • 2021-01-15 09:23

    There are several alternatives. Here are three:

    Most basic, using data.frames :

    df[ df$X1 == "a" , "X1" ] <- df[ df$X1 == "a", "X2" ]
    

    More Terse, using with:

    df$X1 <- with( df, ifelse( X1 == "a", X2, X1 ) )
    

    Most terse and transparent Using data.tables

    library(data.table) ## >= 1.9.0
    setDT(df)           ## converts to data.table by reference, no need for `<-`
    
    df[ X1 == "a", X1 := X2 ]
    
    0 讨论(0)
  • 2021-01-15 09:30

    Here's another approach if you have more than one condition (swap "a" for a vector of values).

    > find.a <- df$X1 %in% "a"
    > df[find.a, "X1"] <- df[find.a, "X2"]
    > df
      X1 X2
    1  D  D
    2  3  W
    3  Q  E
    4  F  F
    5  U  P
    6  B  B
    
    0 讨论(0)
提交回复
热议问题