1

As input we have this data structure:

dframe <- data.frame(id = c(1,2,3), col1 = c(4.2, 1.2,0), su = c(1.2,2.4,0))

The code to create new column

com_num <- with(dframe, pmax(col1, su))
i <- which(dframe[-1] == com_num, arr.ind = TRUE)
dframe$com <- names(dframe[-1])[i[, 2]]
dframe$com_num <- com_num

But this error exist

Error in `$<-.data.frame`(`*tmp*`, com, value = c("col1", "col1", "su",  : 
  replacement has 4 rows, data has 3

I think this is because of zero equal to zero. If this is the situation how can we add when it detect zero equals to zero add a text "zerohere"?

Expected output:

> dframe <- data.frame(id = c(1,2,3), col1 = c(4.2, 1.2,0), su = c(1.2,2.4,0), com = c("col1","su","zerohere"), com_num = c(4.2,2.4,0))
> dframe
  id col1  su      com com_num
1  1  4.2 1.2     col1     4.2
2  2  1.2 2.4       su     2.4
3  3  0.0 0.0 zerohere     0.0
zx8754
  • 52,746
  • 12
  • 114
  • 209
Elr Mant
  • 507
  • 1
  • 4
  • 14
  • @Sotos create two new columns one with the greatest number of the second and third column and according to which one is the greatest the second column receive as value the name of column which has the greatest number in every row – Elr Mant Feb 15 '19 at 12:23
  • 1
    How do you handle ties? i.e. the last row has 0 in both columns. – Sotos Feb 15 '19 at 12:27

0 Answers0