Kumar Abhinav
Kumar Abhinav

Reputation: 6675

How to compare two columns of matrix in r and output the column name in a new vector

I have a matrix with 2 columns and 1000 rows

         first   second
1        0.96     1.34
2        0.67     1.22
3        1        0.87
..
1000      12      11

I want to compare the two columns for every row of matrix and output the value in a new vector with values either "first" or "second"

My output should be

second second first .... first

I want to do this in R

What I have tried so far in R

if(data[2] > data[1]) "second" else "first"

This is returning a vector of only 1 value. Please help

Upvotes: 1

Views: 1458

Answers (2)

Gregor Thomas
Gregor Thomas

Reputation: 145765

Similar to Melissa's answer. This is a little less clear, but a little more efficient than ifelse.

colnames(data)[(data[, 2] > data[, 1]) + 1L]

The comparison will output TRUE or FALSE (equivalent to 1 or 0). When we add 1 it becomes 2 or 1. We can use that to index the column names.

Upvotes: 1

Melissa Key
Melissa Key

Reputation: 4551

You need the vectorized version of if/else. The matrix version:

ifelse(data[,2] > data[,1], "second", "first")

Upvotes: 2

Related Questions