Skip to content

data frame manipulation with conditions

4 messages · A2CT2 Trading, ilai, Arnaud Gaboury

#
Dear list,

n00b question, but still can't find any easy answer.

Here is a df:
x y
1 AA 1
2 BB 2
3 CC 3
4 AA 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.

TY for any help.

Trading
?
A2CT2 Ltd.
#
On Fri, Feb 24, 2012 at 8:11 AM, A2CT2 Trading <trading at a2ct2.com> wrote:
# 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
'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
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 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
To: A2CT2 Trading
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:
# 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
'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
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
______________________________________________
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.
#
Ahh, I see it now.
For some reason your original post popped up on the list again, could
be just my mail server, sorry.
Looks like Uwe gave you the same solution (in two lines for better
clarity) right away. Depending on your level of "noobiness", my advice
would have been to ignore everything after that. Although if the other
approaches worked better for you, cheers.
Again sorry for this double thread.


On Fri, Feb 24, 2012 at 12:31 PM, Arnaud Gaboury
<arnaud.gaboury at a2ct2.com> wrote: