简体   繁体   中英

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM