Reputation: 18875
I would like to merge two columns in R with the following conditions:
if one column has an entry (0, 1, 2), and the other column has './.', use the entry from the first column in the merged column;
if both columns have the same entry (0, 1, 2), use either entry in the merged column;
if one column has an entry (1, 2), and the other column has a different entry (0, 1, 2), use the entry that is lower by 1. For example, if the first column has an entry of '0' and the second column has an entry of '1', use the entry '0' in the merged column.
I literally have no clue how to start. Could someone give me a hint please? thanks
I can do this in Java, but would like to try R first, because the column operation is more straight forward in R.
Upvotes: 0
Views: 733
Reputation: 263301
Perhaps:
apply( cbind(x,y), 1, # This will coerce to character if any "./" present.
function(s) if( "./." %in% s ) { s[ which( s != "./.")]} else{
if( s[1]==s[2] ){ s[1] } else{
min(s)
} }
)
There's no checking for the error of a non-{0,1,2} value, but I took it from the question that such a restriction was expected. A character vector would be returned.
> x
[1] "1" "./." "0" "2"
> y <- rev(x);y
[1] "2" "0" "./." "1"
> apply( cbind(x,y), 1,
+ function(s) if( "./." %in% s ) { s[ which( s != "./.")]} else{
+ if( s[1]==s[2] ){ s[1] } else{
+ min(s)
+ } } )
[1] "1" "0" "0" "1"
Upvotes: 1