3

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 trying to find a solution with for loop, sub, subset, data.table but I have not succeeded. There must be a neat way of doing this.

Example data, where we aim at swapping a in the first column with the corresponding value in the second column and outputting the column again.

df <- data.frame(rbind(c('a','D'),c('H','W'),c('Q','E'),c('a','F'),c('U','P'),c('a','B')))

df$X1 <- as.character(df$X1)
df$X2 <- as.character(df$X2)

# not working
for (i in seq_along(df$X1)){
  a <- df$X1[i]
  b <- df$X2[i]
  x <- ifelse(a[i=='a'], a[i]<-b[i], do.nothing )
  print(x)
}

The output would be like this;

   X1 X2
1  D  a
2  H  W
3  Q  E
4  F  a
5  U  P
6  B  a

(The switch isn't necessary). It's the first column Im interested in.

Any pointer would be appreciated, thanks!

3
  • 2
    with(df, ifelse(X1=="a", X2, NA))? Commented Apr 2, 2014 at 14:27
  • I second @Arun's notion Commented Apr 2, 2014 at 14:44
  • Thanks for commenting. I've tried to make the question somewhat clearer even though the code doesn't make sense. Commented Apr 2, 2014 at 14:49

2 Answers 2

8

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 ]
Sign up to request clarification or add additional context in comments.

2 Comments

+1 From versions >= 1.9.0, setDT(df) should convert data.frame to data.table by reference.
Removed the <- assignment. As the object is modified by reference, it's not necessary. Hope it's alright.
1

Here's another approach if you have more than one condition (swap "a" for a vector of values).

> find.a <- df$X1 %in% "a"
> df[find.a, "X1"] <- df[find.a, "X2"]
> df
  X1 X2
1  D  D
2  3  W
3  Q  E
4  F  F
5  U  P
6  B  B

1 Comment

X1 and X2 should be swapped in the assignment <- I suppose.

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.