Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For each row, get column names where data is equal to a certain value

Tags:

dataframe

r

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  No    
Yes No  Yes No    
Yes No  No  No    
No  No  Yes No

I want to add a 5th column to the data frame named Expected Result if the values on columns 1 to 4 are equal to "Yes". For example, on row 1, I have "Yes" parameters in Column 1 and Column 3. To populate Expected Result column, I would concatenate and add Column1 name and Column 2 name to the result.

Here is the full results expected:

c1, c3    
c1, c2    
c2    
c1    
c1, c3    
c1    
c3

I have the following line of code but something is not quite right:

df$Expected_Result <- colnames(df)[apply(df,1,which(LETTERS="Unfit"))]
like image 680
esh88 Avatar asked Aug 11 '15 14:08

esh88


People also ask

How do you get a specific value of a column from a DataFrame in python?

You can use the loc and iloc functions to access columns in a Pandas DataFrame. Let's see how. If we wanted to access a certain column in our DataFrame, for example the Grades column, we could simply use the loc function and specify the name of the column in order to retrieve it.

How to reference specific cell in pandas?

If you wanted to get a specific cell value from the last Row of Pandas DataFrame, use the negative index to point the rows from last. For example, Index -1 represents the last row and -2 for the second row from the last. Similarly, you should also use -1 for the last column.


1 Answers

An option using data.table

library(data.table)
setDT(df)[, rownum:=1:.N,]
df$Expected_result <- melt(df, "rownum")[, 
                         toString(variable[value=="Yes"]), rownum]$V1
like image 191
ExperimenteR Avatar answered Dec 18 '22 02:12

ExperimenteR