0

I made thi function in R and everything wroks fine:

test<-function (x){
   ma <-apply(x,2,max)
   mi <-apply(x,2,min)
   x2 <-data.frame(x)
   for (i in 1:length(ma))
     x2[,i] <- ifelse(x2[,i]==ma[i],"max",ifelse(x2[,i]==mi[i],"min","FALSE"))
   print (x2)
    }

What should I do if I would make the same adding the information in a new data frame? How can I add new columns automatically?

Thanks a lot

1 Answer 1

1

You can actually do this with the apply function:

test <- function(x) {
  x2 <- apply(x, 2, function(y) {
    ifelse(y==max(y), "max", ifelse(y==min(y), "min", "FALSE"))
  })
  return(as.data.frame(x2))
}

df = data.frame(x = c(2, 1, 3), y = c(1, 2, 3))
test(df)
#       x     y
# 1 FALSE   min
# 2   min FALSE
# 3   max   max
Sign up to request clarification or add additional context in comments.

2 Comments

In the function you made, is x2 tranformed to a matrix and then with 'as.data.frame' in data frame?
Yeah, apply returns a matrix, so I converted it back to a data frame.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.