0

I'm trying to use an object value as new variable name in the ddply statement:

    c<-"Sales_column"
    a1<-ddply(df,.(c1),here(summarize),eval(parse(text=c)) = sum(c3))

It throws a syntax error :

Error: unexpected '=' in a1<-ddply(df,.(c1),here(summarize),eval(parse(text=c)) ="

What am I doing wrong? In this case I want to name the new column as "Sales_column" This code is portion of big code where c value will be changing.

tonytonov
  • 25,060
  • 16
  • 82
  • 98
Sri
  • 1,130
  • 1
  • 15
  • 31

1 Answers1

0

This is one way to do it.

Not sure if it is possible to input the new variable name into ddply in one line as you have tried to do.

Also as a sideopint you shouldn't use "c" as a variable name because it is the r code for a vector and it can get confusing. Other ones to avoid are T (short for TRUE), F (Short for FALSE).

Example Dataframe

df = data.frame(c1 = c(rep("a",5), rep("b", 5)),
                c2 = seq(1,10),
                c3 = rnorm(10))

Solution

library(plyr)
c<-"Sales_column"
a1<-ddply(df,.(c1), here(summarise) , Output = sum(c3))
names(a1) = sub("Output", c, names(a1))
Stuart
  • 1,322
  • 1
  • 13
  • 31
  • Thanks Stuart, That is exactly what I did as a work around - I wanted to find out if there is a direct way to do it in the ddply statement itself – Sri May 05 '14 at 14:34
  • I don't think there is. A few other answers have also not found out how to do this. http://stackoverflow.com/questions/10518925/r-using-ddply-in-a-loop-over-data-frame-columns?rq=1. Maybe a future update of plyr will do it. – Stuart May 05 '14 at 15:11