Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consolidating multiple columns into one column in R

Tags:

dataframe

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!

like image 495
costebk08 Avatar asked Dec 05 '25 00:12

costebk08


1 Answers

Try this:

rep(names(dat),nrow(dat))[c(t(dat)) == 1 & !is.na(c(t(dat)))]
[1] "A" "B" "A" "C"
like image 85
DatamineR Avatar answered Dec 07 '25 15:12

DatamineR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!