Tarak Tarak - 3 months ago 8
R Question

R apply function - which one to use?

I am confused which apply family to use here.
I have a data frame

mydf
as

terms
A
B
C


I want to apply custom function to each of the values and get results in new columns like below

terms Value1 Value2 ResultChar
A 23 45 Good
B 12 34 Average
C 9 23 Poor


custom function is something like myfunc("A") returns a vector like (23, 45, Good)

Any help will be appreciated.

Answer

Looks like you want a data frame output, as you have different data type across columns. So you need define your myfunc to return a data frame.

Consider this toy example:

mydf <- data.frame(terms = letters[1:3], stringsAsFactors = FALSE)
myfunc <- function (u) data.frame(terms = u, one = u, two = paste0(u,u))

Here is one possibility using basic R features:

do.call(rbind, lapply(mydf$terms, myfunc))
#  terms one two
#1     a   a  aa
#2     b   b  bb
#3     c   c  cc

Or you can use adply from plyr package:

library(plyr)
adply(mydf, 1, myfunc)
#  terms terms.1 two
#1     a       a  aa
#2     b       b  bb
#3     c       c  cc

(>_<) it is my first time trying something other than R base for a data frame; not sure why adply returns undesired column names here...

Comments