[R] data frame manipulation with condition

Sarah Goslee sarah.goslee at gmail.com
Fri Feb 24 18:55:20 CET 2012


Whatever makes you happy.

> df1 <-
+ structure(list(x = structure(c(1L, 2L, 2L, 3L), .Label = c("AA",
+ "BB", "CC"), class = "factor"), y = 1:4), .Names = c("x", "y"
+ ), row.names = c(NA, -4L), class = "data.frame")
> mult <- c("AA"=2,"BB"=5,"CC"=1,"DD"=2)
> df1$y * mult[df1$x]
AA BB BB CC
 2 10 15  4
> df1$y * mult[as.character(df1$x)]
AA BB BB CC
 2 10 15  4
>
>
> df2 <- data.frame(x = c("AA","AA","BB","BB","BB","CC","DD","DD"), y = 1:8)
> df2$y * mult[df2$x]
AA AA BB BB BB CC DD DD
 2  4 15 20 25  6 14 16
> df2$y * mult[as.character(df2$x)]
AA AA BB BB BB CC DD DD
 2  4 15 20 25  6 14 16


On Fri, Feb 24, 2012 at 12:52 PM, Arnaud Gaboury
<arnaud.gaboury at a2ct2.com> wrote:
> In fact I need to use William tip: Use mult[as.character(df$x)] instead of mult[df$x].
>
>
> Let's try again with a shorter df as example:
>
> The rule: if AA, then multiply y by 2, if BB multiply y by 5, if CC do nothing, if DD multiply by 2.
>
>
> Let's say day 1 I have df1:
>
> df1 <-
> structure(list(x = structure(c(1L, 2L, 2L, 3L), .Label = c("AA",
> "BB", "CC"), class = "factor"), y = 1:4), .Names = c("x", "y"
> ), row.names = c(NA, -4L), class = "data.frame")
>
>> df1
>   x y
> 1 AA 1
> 2 BB 2
> 3 BB 3
> 4 CC 4
>
>>mult <- c("AA"=2,"BB"=5,"CC"=1,"DD"=2)
>>df1$y <- df1$y * mult[as.character(df1$x)]
>> df1
>   x  y
> 1 AA  2
> 2 BB 10
> 3 BB 15
> 4 CC  4
>
> WORKING
>
> Now day 2 with df2:
>
>>df2 <- data.frame(x = c("AA","AA","BB","BB","BB","CC","DD","DD"), y = 1:8)
>>df2$y <- df2$y * mult[as.character(df2$x)]
>> df2
>   x  y
> 1 AA  2
> 2 AA  4
> 3 BB 15
> 4 BB 20
> 5 BB 25
> 6 CC  6
> 7 DD 14
> 8 DD 16
>
> WORKING
>
>
> Ty both of you and have a good weekend.
>



More information about the R-help mailing list