Search code examples
rapplynamed

Set name on apply results


I am applying a function onto a dataframe.

But unlike sapply and its friends, apply hasn't got any USE.NAME argument to get a named list as returned object.

In this example, I'd like the C column to be the names of the returned list :

df = data.frame(A=c(1,2,3), B=c(9,5,7), C=c("A", "Z", "E"))
apply(df, 1, function(x){
  data.frame(xxx=as.numeric(x[1]) * as.numeric(x[2]))
})
# [[1]]
# xxx
# 1   9
# 
# [[2]]
# xxx
# 1  10
# 
# [[3]]
# xxx
# 1  21

How can I achieve this ?


Solution

  • You could do:

    apply(data.frame(df, row.names = df$C), 1, function(x){
      data.frame(xxx=as.numeric(x[1]) * as.numeric(x[2]))
    })
    #$A
    #  xxx
    #1   9
    #
    #$Z
    #  xxx
    #1  10
    #
    #$E
    #  xxx
    #1  21
    

    Explanation: apply picks up list names from the dimnames of your corresponding MARGIN of your data.frame (in your case MARGIN=1, so list names will correspond to rownames).