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

前端 未结 2 618
伪装坚强ぢ
伪装坚强ぢ 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 ]
    

提交回复
热议问题