Reputation: 39613
I am lloking for a solution to this problem in R. I have a data frame like this:
A1 A2 A3 A4
22 a 1 1
22 b 3 3
21 c 1 2
23 w 1 1
22 a 4 4
I look for a way to change the values in A1
column when A1
and A2
have a value of 22
and a
. In this case when this cristeris is gotten A1
will have a value of 19
, and the data frame will be like this:
A1 A2 A3 A4
19 a 1 1
22 b 3 3
21 c 1 2
23 w 1 1
19 a 4 4
Upvotes: 1
Views: 186
Reputation: 344
If you have large data tables, and speed matters, I would recommend data.table. Here is what it would look like.
library(data.table)
example <- data.table(example)
setkey(example,A1,A2)
example[J(22,"a"), A1 := 19] #uses binary search, faster than example[A1 ==22 & A2 == "a", A1 := 19]
> example
A1 A2 A3 A4
1: 19 a 1 1
2: 22 b 3 3
3: 21 c 1 2
4: 23 w 1 1
5: 19 a 4 4
Feel free to compare times for the data.frame and data.table solutions on a larger data set.
Upvotes: 2
Reputation: 7794
example <- data.frame(A1=c(22,22,21,23,22),A2=c("a","b","c","w","a"),A3=c(1,3,1,1,4),A4=c(1,3,2,1,4))
example$A1[example$A1==22 & example$A2=="a"] <- 19
> example
A1 A2 A3 A4
1 19 a 1 1
2 22 b 3 3
3 21 c 1 2
4 23 w 1 1
5 19 a 4 4
Upvotes: 1