# [R] reduce three columns to one with the colnames

Gabor Grothendieck ggrothendieck at gmail.com
Mon May 13 17:39:46 CEST 2013

```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

```