1

I am trying to use the max function in R by piping it. But when I do the same, the result is a bit odd. Instead of giving the max function between 0 and the value in the respective column, this returns the max value on the entire column.

Can someone tell me how to find the max between 0 and vales in a column within a data frame by piping itself.

Attached is the data frame I am working on:

structure(list(Model = c("3M-MA", "3M-MA", "3M-MA", "3M-MA", 
"3M-MA", "3M-MA"), `12NC's` = c("X12-57", "X12-78", "X12-65", 
"X12-75", "X12-62", "X12-35"), `Avg Price` = c(17.5, 24.2, 110.4, 
54.9, 23.5, 67.4), Act = c(68, 75, 87, 28, 33, 6), Fct = c(24, 
72, 54, 20, 18, 2), Value_Act = c(1190, 1815, 9604.8, 1537.2, 
775.5, 404.4), Value_Fct = c(420, 1742.4, 5961.6, 1098, 423, 
134.8), FC = c(20.3389830508475, 69.2307692307692, 38.0952380952381, 
0, 54.5454545454545, 33.3333333333333), FC1 = c(69.2307692307692, 
69.2307692307692, 69.2307692307692, 69.2307692307692, 69.2307692307692, 
69.2307692307692)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

Attached is the code which I wrote the same:

Test1 <- read_excel("C:/X/X/X/X/Test1.xlsx")
Test1 <- Test1 %>% 
  mutate(FC1 = max(Test1$FC,0))

The Expected Output is:

enter image description here

jpsmith
  • 11,023
  • 5
  • 15
  • 36
user20203146
  • 447
  • 7

1 Answers1

0

Use pmax:

max() won't work because using max will return the maximum value of the entire column (in this case 69.2).

pmax will find the maximum between 0 and each element of the column.

library(dplyr)

Test1 %>% 
  mutate(FC1 = pmax(FC, 0))
Model `12NC's` `Avg Price`   Act   Fct Value_Act Value_Fct    FC   FC1
  <chr> <chr>          <dbl> <dbl> <dbl>     <dbl>     <dbl> <dbl> <dbl>
1 3M-MA X12-57          17.5    68    24     1190       420   20.3  20.3
2 3M-MA X12-78          24.2    75    72     1815      1742.  69.2  69.2
3 3M-MA X12-65         110.     87    54     9605.     5962.  38.1  38.1
4 3M-MA X12-75          54.9    28    20     1537.     1098    0     0  
5 3M-MA X12-62          23.5    33    18      776.      423   54.5  54.5
6 3M-MA X12-35          67.4     6     2      404.      135.  33.3  33.3
TarJae
  • 72,363
  • 6
  • 19
  • 66