[R] Using if, else statements
Patrick Burns
pburns at pburns.seanet.com
Wed Jul 23 19:15:20 CEST 2008
jjdow <- sample(c('Sun', 'Mon', 'Tues'), 10, replace=TRUE)
jjdata <- data.frame(admission=1:10, d.o.w.=jjdow)
#> jjdata
# admission d.o.w.
#1 1 Tues
#2 2 Tues
#3 3 Tues
#4 4 Sun
#5 5 Mon
#6 6 Mon
#7 7 Sun
#8 8 Tues
#9 9 Sun
#10 10 Mon
new.jjdata <- within(jjdata, admission <- ifelse(d.o.w. == 'Sun',
1.21 * admission, ifelse(d.o.w.=='Mon', .91 * admission, admission)))
#> new.jjdata
# admission d.o.w.
#1 1.00 Tues
#2 2.00 Tues
#3 3.00 Tues
#4 4.84 Sun
#5 4.55 Mon
#6 5.46 Mon
#7 8.47 Sun
#8 8.00 Tues
#9 10.89 Sun
#10 9.10 Mon
Pat
Robin Williams wrote:
> No, this is my first experience with any powerful statistical package. Any
> code much appreciated.
>
> -----Original Message-----
> From: Patrick Burns [mailto:pburns at pburns.seanet.com]
> Sent: 23 July 2008 17:44
> To: Robin Williams
> Subject: Re: [R] Using if, else statements
>
> You might have found 'ifelse' in S Poetry, which
> is one way of solving your problem.
>
>
> Patrick Burns
> patrick at burns-stat.com
> +44 (0)20 8525 0696
> http://www.burns-stat.com
> (home of S Poetry and "A Guide for the Unwilling S User")
>
> Robin Williams wrote:
>
>> Hi all,
>>
>> Again I have searched the net and so on, without finding an answer to this
>> surely simple problem. A short bit of code would be appreciated.
>>
>> I have a object named `data' with the following column headings.
>>
>> Date, maxitemp, minitemp, admissions, d.o.w.
>>
>> Where d.o.w. is day of the week, written "Sun" "Mon" etc.
>>
>> I just need to scale the Monday admissions by 0.91, the Saturday
>> admissions by 1.21 and the Sunday admissions by 1.22. So basically what I
>> want is:
>>
>> If d.o.w. == "Sat"
>>
>> Multiply Sat admissions by 1.21.
>>
>> (Now do I need an else statement here, or can I just do another)
>>
>> If d.o.w. == "Sun"
>>
>> Multiply "Sun" admissions by 1.22
>>
>> (and finally)
>>
>> If d.o.w. == "Mon"
>>
>> Multiply Monday admissions by 0.91.
>>
>> Else do nothing.
>>
>> I assume in my code I need to specify that I am using the data.frame
>> `data', so do I need to write things like
>>
>> If(data[d.o.w.]=="Mon")
>>
>> I would then like to round the new admissions to integers (I assume I
>>
> just
>
>> use round(data$admissions)), and output the new data to another csv file.
>>
>> I could of course do this in excel but I will need to extend this type
>>
> of
>
>> idea in the future so I would like to master it in R.
>>
>> Many thanks for any help/code.
>>
>> Robin Williams.
>>
>>
>> [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> 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