Tarak
Tarak

Reputation: 1075

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.

Upvotes: 0

Views: 115

Answers (2)

akrun
akrun

Reputation: 886948

We can use rbindlist with lapply. It would be more efficient

 library(data.table)
 rbindlist(lapply(mydf$terms, myfunc))

If needed, I can show the benchmarks. But, they are already shown here

Upvotes: 3

Zheyuan Li
Zheyuan Li

Reputation: 73265

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...

Upvotes: 4

Related Questions