[R] How to add a variable to a dataframe whose values are conditional upon the values of an existing variable
Andrew Miles
rstuff.miles at gmail.com
Fri Feb 26 20:46:18 CET 2010
You could also try a series of simple ifelse statements. I just tried
the following and got it to work, though I am sure there is a faster
way.
t=c("cow", "dog", "chick")
y=c(1,3,4)
mat=cbind(t,y)
mat=as.data.frame(mat)
> mat
t y
1 cow 1
2 dog 3
3 chick 4
mat$g=ifelse(mat$t=="cow", 1, 6)
mat$g=ifelse(mat$t=="dog", 2, mat$g)
mat$g=ifelse(mat$t=="chick", 3, mat$g)
> mat
t y g
1 cow 1 1
2 dog 3 2
3 chick 4 3
To days of the week would only be 7 statements.
Andrew Miles
Department of Sociology
Duke University
On Feb 26, 2010, at 2:31 PM, Steve Matco wrote:
> Hi everyone,
>
> I am at my wits end with what I believe would be considered simple
> by a more experienced R user. I want to know how to add a variable
> to a dataframe whose values are conditional on the values of an
> existing variable. I can't seem to make an ifelse statement work for
> my situation. The existing variable in my dataframe is a character
> variable named DOW which contains abbreviated day names (SAT, SUN,
> MON.....FRI). I want to add a numerical variable named DOW1 to my
> dataframe that will take on the value 1 if DOW equals "SAT", 2 if
> DOW equals "SUN", 3 if DOW equals "MON",.....,7 if DOW equals "FRI".
> I know this must be a simple problem but I have searched everywhere
> and tried everything I could think of. Any help would be greatly
> appreciated.
>
> Thank you,
>
> Mike
>
>
>
>
> ______________________________________________
> 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