Home > Software design >  Combine two columns in a data frame and select which value to take for each row by referencing anoth
Combine two columns in a data frame and select which value to take for each row by referencing anoth

Time:12-15

I have the following dataframe.

a <- c(1,2,1,3)
b <- c(0.5, 0.6, 0.7, 0.3)
d <- c(0.4, 0.3, 0.6, 0.4)

df <- data.frame(a,b,d)

df

#output
#  a   b   d
#1 1 0.5 0.4
#2 2 0.6 0.3
#3 1 0.7 0.6
#4 3 0.3 0.4

I want to combine column b and d into a new column and decide which column value to take for each row based on column a. If a = 1 I want to take the value from column d. If a doesn't equal 1 the new column will take the value from column b for that row.

I tried the following...

df$new <- c(df[df$a != 1, "b"], df[df$a == 1, "d"])

df

#output
#  a   b   d new
#1 1 0.5 0.4 0.6
#2 2 0.6 0.3 0.3
#3 1 0.7 0.6 0.4
#4 3 0.3 0.4 0.6

...but the rows don't line up properly. How can I combine these two columns in this manner without losing the row index to achieve the desired output shown below?

#desired output
#  a   b   d new
#1 1 0.5 0.4 0.4
#2 2 0.6 0.3 0.6
#3 1 0.7 0.6 0.6
#4 3 0.3 0.4 0.3

CodePudding user response:

This is what the ifelse function is for:

df$new <- ifelse(df$a==1, df$d, df$b)

Your version didn't work as it included all the a!=1 values first and then the a==1 values afterwards.

  •  Tags:  
  • r
  • Related