costebk08
costebk08

Reputation: 1359

Consolidating multiple columns into one column in R

I have a data-frame that looks something like"

print(dat)
A  B  C
1  NA NA
NA 1  NA
1  NA NA
NA NA 1

Reproducible by:

dat <- data.frame(A=c(1,NA,1,NA), B=c(NA,1,NA,NA), C=c(NA,NA,NA,1))

So that if a 1 is found in given column the other two columns will have NAs. I am trying to consolidate this information into 1 column so it looks like:

print(dat)
A
B
A
C

I have tried:

dat<-ifelse(dat$A==1,"A",ifelse(dat$B==1,"B",ifelse(dat$C==1,"C","NA")))

But it does not work. Any suggestions? Thanks!

Upvotes: 2

Views: 119

Answers (5)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193497

To add to the existing options, try:

na.omit(stack(dat))$ind
## [1] A A B C
## Levels: A B C

Upvotes: 1

akrun
akrun

Reputation: 886938

Another option is

names(dat)[+(!is.na(dat)) %*% seq_along(dat)]
#[1] "A" "B" "A" "C"

Upvotes: 2

thelatemail
thelatemail

Reputation: 93803

max.col is the winner for these sorts of tasks:

colnames(dat)[max.col(!is.na(dat))]
#[1] "A" "B" "A" "C"

Upvotes: 3

Marat Talipov
Marat Talipov

Reputation: 13304

Another way:

> t(dat) %>% melt() %>% na.omit() %>% select(X1)
   X1
1   A
5   B
7   A
12  C

Upvotes: 2

DatamineR
DatamineR

Reputation: 9618

Try this:

rep(names(dat),nrow(dat))[c(t(dat)) == 1 & !is.na(c(t(dat)))]
[1] "A" "B" "A" "C"

Upvotes: 4

Related Questions