[R] reduce three columns to one with the colnames

Bert Gunter gunter.berton at gene.com
Mon May 13 18:21:18 CEST 2013


... and I could not resist adding (assuming the vectors are all  in a
data frame or matrix, yourdat):

apply(yourdat,1,function(x)c("blue","green","red")[as.logical(x)])

Cheers,
Bert



On Mon, May 13, 2013 at 8:39 AM, Gabor Grothendieck
<ggrothendieck at gmail.com> wrote:
> On Mon, May 13, 2013 at 10:24 AM, David Studer <studerov at gmail.com> wrote:
>> Hello everybody,
>>
>> I have three variables "blue", "green" and "red" containing values 0 (no)
>> and 1 (yes).
>>
>> How can I easily create another variable "colors" with the values "blue",
>> "green" and "red"?
>>
>
> Suppose
>
> blue <- c(1, 0, 0, 1)
> green <- c(0, 0, 1, 0)
> red <- c(0, 1, 0, 0)
>
> Here are a few possibilities:
>
> # 1
> factor(blue + 2 * green + 3 * red, labels = c("blue", "green", "red"))
>
> # 2
> paste0(
>    ifelse(blue, "blue", ""),
>    ifelse(green, "green", ""),
>    ifelse(red, "red", "")
> )
>
> # 3
> newvar <- character(length(blue))
> newvar[!!blue] <- "blue"
> newvar[!!green] <- "green"
> newvar[!!red] <- "red"
> newvar
>
> # 4
> c("blue", "green", "red")[blue + 2 * red + 3 * green]
>
> # 5
> library(car)
> recode(blue + 2 * green + 3 * red, "1='blue'; 2='green'; 3='red'")
>
>
> --
> Statistics & Software Consulting
> GKX Group, GKX Associates Inc.
> tel: 1-877-GKX-GROUP
> email: ggrothendieck at gmail.com
>
> ______________________________________________
> 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.



-- 

Bert Gunter
Genentech Nonclinical Biostatistics

Internal Contact Info:
Phone: 467-7374
Website:
http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm



More information about the R-help mailing list