1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 With the caveat that that's a vector scan in i (usually discouraged). Binary search using setkey will perform even better, as per intro vignette.
1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.