[R] Help with combining functions
arun
smartpink111 at yahoo.com
Tue Oct 15 04:22:11 CEST 2013
Using ?replace()
vec2 <- replace(n,c(n[n%%3==0 & !n%%5==0],n[!n%%3==0 & n%%5==0],n[n%%15==0]),c(rep(c("heads","tails","headstails"),c(sum(n%%3==0 & !n%%5==0),sum(!n%%3==0 & n%%5==0),sum(n%%15==0)))))
identical(vec1,vec2)
#[1] TRUE
#or
library(plyr)
vec3 <- mapvalues(n,c(n[n%%3==0 & !n%%5==0],n[!n%%3==0 & n%%5==0],n[n%%15==0]),c(rep(c("heads","tails","headstails"),c(sum(n%%3==0 & !n%%5==0),sum(!n%%3==0 & n%%5==0),sum(n%%15==0)))))
identical(vec1,vec3)
#[1] TRUE
A.K.
On Monday, October 14, 2013 1:24 PM, arun <smartpink111 at yahoo.com> wrote:
Hi,
Try:
vec1 <- as.character(factor(1*(n%%3==0)+2*(n%%5==0)+3*(n%%15==0),labels=c("Other","heads","tails","headstails")))
vec1[vec1=="Other"] <- which(vec1=="Other")
vec1[1:6]
#[1] "1" "2" "heads" "4" "tails" "heads"
A.K.
On Monday, October 14, 2013 12:57 PM, Kile Green <Kile.Green at newcastle.ac.uk> wrote:
Hi,
I am very new to 'R' ("discovered" it about 2 months ago) and have been trying to teach myself the language using online guides, however I am not a programmer or statistician and so progress is slow.
As an exercise, I have been trying to generate the numbers 1 to 100 and replace multiples of 3 with the text "heads", multiples of 5 with the text "tails" and multiples of both 3 and 5 with the text "headstails".
So far I have managed to write the functions individually with:
> n=c(1:100)
> a=replace(n,n%%3==0,"heads")
> b=replace(n,n%%5==0,"tails")
> c=replace(n,n%%15==0,"headstails")
I would like to combine these functions into a single process to produce an output along the lines of:
1,2,"heads",4,"tails","heads",7,8,"heads","tails"... etc
I tried the following, without success:
> replace(n,c(n%%3==0,n%%5==0,n%%15==0),c("heads","tails,"headstails"))
As an 'R' novice I don't really have an idea of how I should approach this problem and unfortunately I have had problems trying to apply the answers given to other replace() and c() questions to my example.
I would be grateful if someone could point me in the right direction or provide a similar example of combining simple functions without just giving the answer away - i'd like to learn how to use 'R', rather than just be told the answer.
Regards,
Kile
[[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