How to extract column names for each row using column values inR?

Viewed 65

I have a dataframe that calculates the user similarity.

enter image description here

I want to extract a list of users with a similarity of 0.5 or higher for each user.

like this...

enter image description here

Is there any way to get this result at once without using a loop?

1 Answers

Set the diagonal to 0 since you don't want to include the similarity of the user with itself and use apply rowwise.

cols <- colnames(df)
diag(df) <- 0
result <- data.frame(userid = cols, 
                     similar_user = apply(df >= 0.5, 1, function(x) toString(cols[x])))

result
Related