I have a dataframe something this:
id <- c(1, 2, 3, 4, 5, 6, 7)
var1 <- c(1, NA, 2, NA, 1, 1, 2)
var2 <- c(1, 1, 2, 2, NA, 2, 2)
However, how do I manage to create a new vector, which takes the values from var2, and replace it with NAs in var1 and otherwise just takes the value (1 or 2) from var1, as long as it has one?
I'm thinking something like:
id <- c(1, 2, 3, 4, 5, 6, 7)
var1 <- c(1, NA, 2, NA, 1, 1, 2)
var2 <- c(1, 1, 2, 2, NA, 2, 2)
newvar <- c(1, 1, 2, 2, 1, 1, 2)
The same goes for another dataframe, in which there are more vectors:
id <- c(1, 2, 3, 4, 5, 6, 7)
var1 <- c(1, NA,2, NA,NA,1, 2)
var2 <- c(1, 1, 2, 2, NA,2, 2)
var3 <- c(2, 1, 2, 1, 1, 1, 2)
var4 <- c(1, 1, 2, NA,2, 1, 2)
In this case, I want to create another vector "newvar", which takes the dominant value from the var2, var3 and var4, and replace it with NA in var1.
So the starting point will always be what is in var1. However for id4 and id5 fx, there is no dominant value in the other variables - then i want to replace NA with values from the first variable with values, in this to two cases values from var 2 and var3 respectively.
id <- c(1, 2, 3, 4, 5, 6, 7)
var1 <- c(1, NA,2, NA,NA,1, 2)
var2 <- c(1, 1, 2, 2, NA,2, 2)
var3 <- c(2, 1, 2, 1, 1, 1, 2)
var4 <- c(1, 1, 2, NA,2, 1, 2)
newvar <- c(1, 1, 2, 2, 1, 1, 2)
How can this be done in an easy way?
Thank you!