[R] data frame manipulation with conditions

ilai keren at math.montana.edu
Fri Feb 24 20:14:11 CET 2012


On Fri, Feb 24, 2012 at 8:11 AM, A2CT2 Trading <trading at a2ct2.com> wrote:
> Dear list,
>
> n00b question, but still can't find any easy answer.
>
> Here is a df:
>
>> df<-data.frame(cbind(x=c("AA","BB","CC","AA"),y=1:4))

# No, your y is a factor
 str(df)
'data.frame':	4 obs. of  2 variables:
 $ x: Factor w/ 3 levels "AA","BB","CC": 1 2 3 1
 $ y: Factor w/ 4 levels "1","2","3","4": 1 2 3 4

# You want to remove the cbind
> df<-data.frame(x=c("AA","BB","CC","AA"),y=1:4)
> str(df)
'data.frame':	4 obs. of  2 variables:
 $ x: Factor w/ 3 levels "AA","BB","CC": 1 2 3 1
 $ y: int  1 2 3 4

> I want to modify this df this way :
>  if df$x=="AA" then df$y=df$y*10
>  if df$x=="BB" then df$y=df$y*25
>
> and so on with other conditions.
>

 df$y<- df$y * c(10,25,.5)[df$x]
[1] 10.0 50.0  1.5 40.0
 # 1*10 2*25 3*.5 4*10

HTH

Elai

> TY for any help.
>
> Trading
>
> A2CT2 Ltd.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list