[R] Replace row value with corresponding column name

arun smartpink111 at yahoo.com
Sat Jun 1 00:59:19 CEST 2013


HI,
Try this:
data1 <- data.frame("var1"=c(1,2,3),"var2"=c("A","B","C"),"var3"=c(4,5,6)) #your example

data2 <- data.frame("var1"=c(1,2,3),"var2"=c("5","6","9"),"var3"=c(4,5,6)) #your example
data3<- data.frame(var1=c(5,6,5,5),var2=c(4,4,5,3),var3=c(1,4,3,5))
 data4<- data.frame(var1=c(1,2,3),var2=c(1,4,6))
fun1<- function(dat,value){

 cols<- colnames(dat)
indx1<- rowSums(dat==value)
 if(any(indx1>1)){
 lst<-apply(dat,1,function(x) cols[x==value])
 lst[lapply(lst,length)==0]<-NA
 dat$newvar<-lst
dat
 }
else{    
 indx2<- (dat==value)%*%seq_along(cols)
 indx2[indx2==0]<-NA
 dat$newvar<-cols[indx2]
 dat
}
 }

data1New<-fun1(data1,5)
 data1New
#  var1 var2 var3 newvar
#1    1    A    4   <NA>
#2    2    B    5   var3
#3    3    C    6   <NA>

data2New<-fun1(data2,5)
 data2New
#  var1 var2 var3 newvar
#1    1    5    4   var2
#2    2    6    5   var3
#3    3    9    6   <NA>
data3New<- fun1(data3,5)
 data3New
#  var1 var2 var3     newvar
#1    5    4    1       var1
#2    6    4    4         NA
#    5    5    3 var1, var2
#4    5    3    5 var1, var3

fun1(data4,5)
#  var1 var2 newvar
#1    1    1   <NA>
#2    2    4   <NA>
#3    3    6   <NA>


A.K.






Dear R Community, 
I tried searching the archives for the question below, but couldn't find what I was looking for - please help! 

Suppose I  have a data frame like the following: 
data <- 
data.frame("var1"=c(1,2,3),"var2"=c("A","B","C"),"var3"=c(4,5,6)) > 
data <- 
data.frame("var1"=c(1,2,3),"var2"=c("5","6","9"),"var"=c(4,5,6)) 
> data 
  var1 var2 var3 
1    1    5   4 
2    2    6   5 
3    3    9   6 

I would like to create a new variable that identifies the column name where the value 5 appears.  the results should look 
like below: 
  var1 var2 var3 newvar 
1    1    5    4   var2 
2    2    6    5   var3 
3    3    9    6   <NA>
Can anyone share code that shows the most efficient way to accomplish this? 
Any help is much appreciated. 
Thanks!



More information about the R-help mailing list