Get column names where dat is equal to

后端 未结 3 1350
Happy的楠姐
Happy的楠姐 2021-01-12 18:12

I have a data frame (df) with 7 rows and 4 columns (named c1, c2, c3, c4):

c1  c2  c3  c4
Yes No  Yes No    
Yes Yes No  No    
No  Yes No  No    
Yes No  No         


        
3条回答
  •  死守一世寂寞
    2021-01-12 18:47

    You could try something like:

    colnames(df) <- c("c1", "c2", "c3", "c4")
    
    test <- (apply(df,1,function(x) which(x=="Yes")))
    
    df$cols <- lapply(test,names)
    

    This was along the lines of what you were initially trying I think.

    To tidy the output you could:

     df$cols <- gsub("c(", "", df$cols, fixed = TRUE)
    
     df$cols <- gsub(")", "", df$cols, fixed = TRUE)
    

    This removes the c().

提交回复
热议问题