# [R] data frame manipulation with conditions

Arnaud Gaboury arnaud.gaboury at a2ct2.com
Fri Feb 24 20:31:27 CET 2012

```TY Elai for your answer. One solution has been given earlier in this list by Sarah Goslee and William Dunlap.

Arnaud Gaboury

A2CT2 Ltd.

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of ilai
Sent: vendredi 24 février 2012 20:14
Cc: r-help at r-project.org
Subject: Re: [R] data frame manipulation with conditions

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.
>
>
> A2CT2 Ltd.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help