Dear Johannes,
You can use cascading ifelse()s:
> df$A <- with(df, ifelse(A <= 3, "x", ifelse(A > 3 &
A <= 8, "y", "z")))
> df$A
[1] "x" "x" "x" "y" "y"
This command assumes that you want all values that don't map into
"x"s and
"y"s to be "z"s, but you could adapt it if that's not
what you want (and no
values in your example become "z"s anyway).
I hope this helps,
John
--------------------------------
John Fox
Senator William McMaster
Professor of Social Statistics
Department of Sociology
McMaster University
Hamilton, Ontario, Canada
web: socserv.mcmaster.ca/jfox
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at
r-project.org]
On> Behalf Of johannes rara
> Sent: March-30-10 7:31 AM
> To: r-help at r-project.org
> Subject: [R] How to recode variables using base R
>
> Hi,
>
> Is there an efficient way recoding variables in a data.frame using
> base R? My purpose is to create
> new variables and attach them into old data.frame. The basic idea is
> shown below, but how to create recoding for A, B and C and assing them
> into new variables?
>
> df <- data.frame(A = c(1:5),
> B = c(3,6,2,8,10),
> C = c(0,15,5,9,12))
>
> df$A[df$A <= 3] <- "x"
> df$A[df$A > 3 & df$A <= 8] <- "y"
> df$A[df$A <= 16] <- "z"
>
> Thanks,
> -J
>
> ______________________________________________
> 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.