statssyboy
statssyboy

Reputation: 89

Getting the wanted value across two columns in R

I'm currently trying to find a way to get a specific ID as a new column.

My data.frame looks like this below:

V1 V2 
A B
C A
D A
A E

What I'm trying to get:

V1 V2 V3 
A B B 
C A C 
D A D 
A E E 

Essentially, a new column that isn't A, but I'm not sure how to do this.

Upvotes: 1

Views: 31

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101099

Another base R option (would be slow when with many rows)

df$V3 <- apply(df,1,setdiff,"A")

such that

> df
  V1 V2 V3
1  A  B  B
2  C  A  C
3  E  A  E
4  A  D  D

Upvotes: 0

akrun
akrun

Reputation: 886948

We can use an ifelse

df1$V3 <- with(df1, ifelse(V1 == 'A', V2, V1))
df1
#  V1 V2 V3
#1  A  B  B
#2  C  A  C
#3  D  A  D
#4  A  E  E

Or as @markus mentioned

with(df1, replace(V1, V1 == "A", V2[V1 == "A"]))

Or another option is to create a row/column index with max.col and then extract the values based on the index

df1[cbind(seq_len(nrow(df1)), max.col(df1 != 'A'))]
#[1] "B" "C" "D" "E"

data

df1 <- structure(list(V1 = c("A", "C", "D", "A"), V2 = c("B", "A", "A", 
"E")), class = "data.frame", row.names = c(NA, -4L))

Upvotes: 2

Related Questions