vctrd vctrd - 2 months ago 6
R Question

Apply a function by row on a dataframe independently of the number of columns

I'd like to apply a function by rows on a data.frame to concatenate column titles depending on the value in the row.

df
A B
1 TRUE TRUE
2 FALSE TRUE
3 FALSE FALSE

A B Result
1 TRUE TRUE A / B
2 FALSE TRUE B
3 FALSE FALSE NA


I read about dplyr using mutate() and rowwise(), but I don't know how to apply them since the columns aren't constants.

for a row "i" I would do something like:

paste(names(df)[as.logical(df[i,])], collapse = ' / ')


Any help would be welcome.

Thank you.

Answer

We can use apply with MARGIN=1 to loop over the rows, subset the names of the vector using the logical vector as index and paste them together.

df$Result <- apply(df, 1, FUN = function(x) paste(names(x)[x], collapse=" / "))