I am trying to merge 2 columns within the same dataset in order to condense the number of columns.
The dataset currently looks like this:
Year Var1 Var2
2014 NA 123
2014 NA 155
2015 541 NA
2015 432 NA
2016 NA 124
etc
I wish the dataset to look like
Year Var1/2
2014 123
2014 155
2015 541
2015 432
2016 124
Any Help is grealty apprecitated.
You should be able to just use with(mydf, pmax(Var1, Var2, na.rm = TRUE))
.
Here's a sample data.frame
. Note row 5.
mydf <- structure(list(Year = c(2014L, 2014L, 2015L, 2015L, 2016L), Var1 = c(NA,
NA, 541L, 432L, NA), Var2 = c(123L, 155L, NA, NA, NA)), .Names = c("Year",
"Var1", "Var2"), row.names = c(NA, 5L), class = "data.frame")
mydf
## Year Var1 Var2
## 1 2014 NA 123
## 2 2014 NA 155
## 3 2015 541 NA
## 4 2015 432 NA
## 5 2016 NA NA
with(mydf, pmax(Var1, Var2, na.rm = TRUE))
## [1] 123 155 541 432 NA
Assign it to a column and you're good to go.