I have a data frame. I’m trying to create a dummy variable that is the maximum of 3 columns for a given row.
for(i in 1:nrow(data))
{
data[i,]$max_metric <- max(data[i,]$a,
data[i,]$b,
data[i,]$c)
}
This code works, but it’s definitely not the best way to do it. Are there any other ways to do this?
Use
pmax, which takes the element-wise maximum of all arguments passed to it. However, this means you can’t just pass the whole data.frame.But you can pass each column of the data.frame to
pmaxviado.callbecause the second argument todo.callshould be a list and data.frames are lists (with some attributes).