Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recoding data frame column based on multiple columns [duplicate]

Tags:

dataframe

r

How do I recode a column based on values from other columns? Say I have the below data frame and I want to recode df$Col3 so that the value is 0 if df$Col1 == x and df$Col2 == a.

> df <- data.frame(a=c(rep("x",3),rep("y",3),rep("x",4)),letters[c(1:5,3,4:1)],1:10)
> names(df)<-c("Col1","Col2","Col3")
> df
   Col1 Col2 Col3
1     x    a    1
2     x    b    2
3     x    c    3
4     y    d    4
5     y    e    5
6     y    c    6
7     x    d    7
8     x    c    8
9     x    b    9
10    x    a   10
like image 446
lolatu2 Avatar asked Oct 18 '25 16:10

lolatu2


1 Answers

You can use ifelse

> df$Col3  <- with(df, ifelse(Col1=='x' & Col2=='a', 0, Col3))
> df
   Col1 Col2 Col3
1     x    a    0
2     x    b    2
3     x    c    3
4     y    d    4
5     y    e    5
6     y    c    6
7     x    d    7
8     x    c    8
9     x    b    9
10    x    a    0
like image 73
Jilber Urbina Avatar answered Oct 21 '25 06:10

Jilber Urbina