I have a dataset with two columns and I would like to combine them into a single column.
Here is an example:
newdata<-data.frame(Tow.y=c(21,"NA","NA","NA",22,"NA","NA"),Tow=c("NA","NA","NA",21,"NA","NA",22))
newdata$Tow.y<-as.numeric(as.character(newdata$Tow.y))
newdata$Tow<-as.numeric(as.character(newdata$Tow))
newdata
Tow.y Tow
1 21 NA
2 NA NA
3 NA NA
4 NA 21
5 22 NA
6 NA NA
7 NA 22
What I would like is to have another column that takes the non NA values from each row for the other two columns and leaves all of the other rows with NAs as NAs.
Like this
newdata
Tow.y Tow Station
1 21 NA 21
2 NA NA NA
3 NA NA NA
4 NA 21 21
5 22 NA 22
6 NA NA NA
7 NA 22 22
I thought I could use an ifelse statement, but it is not working. Only one of the two columns is being added to the new column.
Example ifelse statement:
newdata$Station<-ifelse(newdata$Tow.y<0 & is.na(newdata$Tow), newdata$Tow.y,
ifelse(is.na(newdata$Tow.y) & is.na(newdata$Tow), "NA", ifelse(is.na(newdata$Tow.y) & newdata$Tow<0, newdata$Tow,
"check")))
I have tried and and if with no luck in the code.