Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

dataframe - Change specific value in column with conditions in R

I have a daframe such as :

COL1       COL2 
C.lupus    10
C.lupus    20
C.famil    90
O.cuniculus 30
O.cuniculus 70 
O.cuniculus 10 

and I would like tu replace each COL1 == to O.cuniculus and where COL2 < 50 by O.spatacus

Here I should then get :

  COL1       COL2 
    C.lupus    10
    C.lupus    20
    C.famil    90
    O.spatacus 30
    O.cuniculus 70 
    O.spatacus 10 

Thanks a lot for your help

question from:https://stackoverflow.com/questions/65540891/change-specific-value-in-column-with-conditions-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A base R option using replace

transform(
  df,
  COL1 = replace(COL1, COL1 == "O.cuniculus" & COL2 < 50, "O.spatacus")
)

gives

         COL1 COL2
1     C.lupus   10
2     C.lupus   20
3     C.famil   90
4  O.spatacus   30
5 O.cuniculus   70
6  O.spatacus   10

A data.table option works in a similar manner

setDT(df)[COL1 == "O.cuniculus" & COL2 < 50, COL1 := "O.spatacus"]

such that

          COL1 COL2
1:     C.lupus   10
2:     C.lupus   20
3:     C.famil   90
4:  O.spatacus   30
5: O.cuniculus   70
6:  O.spatacus   10

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...