user3570187 user3570187 - 1 month ago 4
R Question

Getting maximum value from a group of values and dividing the yearly yield

I am trying to create a new variable which takes the maximum value from one array and divides by the

yield of the same product. For example ,

orangesum<- c(12,20,NA,60)
applesum<- c(4,NA,222,34)
grapesum<- c(4,33,NA,223)
orangeysum<- c(400,220,330,456)
appleysum <- c(220,340,394,349)
grapeysum<- c(33,344,33,2345)
year<- c(2008,2009,2010,2011)

df<- data.frame(orangesum,applesum, grapesum, orangeysum, appleysum,grapeysum, year)

I want to create a variable called
which is the maximum value in the record/maximum value of the yearly yield of that type of product. so in the first row it would be 12/400, 33/344, 222/394,223/2345. Any suggestions?


We can use pmax to get the max value of rows for the subset of datasets i.e df[1:3] and df[4:6] (which corresponds to columns named like *sum vs. *ysum) and divide those to create the 'maxyield':

df$maxyield <-, c(df[1:3], na.rm=TRUE))/, c(df[4:6], na.rm = TRUE))
#[1] 0.03000000 0.09593023 0.56345178 0.09509595