[R] How to add a variable to a dataframe whose values are conditional upon the values of an existing variable
Daniel Malter
daniel at umd.edu
Fri Feb 26 20:48:22 CET 2010
Hi, two approaches at least.
a. a nested ifelse statement
b. merging the original data frame with DOW in it with a data frame that
holds the day "MON" to "SUN" and their indicators.
Both approaches illustrated below:
DOW=rep(c("MON","TUE"),100)
#nested ifelse approach
DOW.ind=ifelse(DOW=="MON",1,ifelse(DOW=="TUE",2,0))
#continue to nest ifelse statements for more days
DOW.ind
#merging approach
day=c("MON","TUE")
ind=c(1,2)
ind.frame=data.frame(day,ind)
merge(data.frame(DOW),ind.frame,by.x="DOW",by.y="day",all.x=T,all.y=F)
HTH,
Daniel
-------------------------
cuncta stricte discussurus
-------------------------
-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of Steve Matco
Sent: Friday, February 26, 2010 2:32 PM
To: r-help at r-project.org
Subject: [R] How to add a variable to a dataframe whose values are
conditional upon the values of an existing variable
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