Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common elements by columns in high-dimensional matrix

I have a data like original with much more columns.

id <- c('A','B','C', 'D', 'E', 'F', 'G')
month <- c('NA', 'D', 'H', 'I', 'A', 'B', 'NA')
iso <- c('NA', 'NA', 'NA', 'A', 'B', 'C', 'NA')
original <- data.frame(id, month, iso)

I want to create a string containing all common elements found in the columns, like string common:

common <- c("A", "B")

I have found posts like: R: How can I find the intersection of elements from two rows of a dataframe? or like: How to find common elements from multiple vectors?

But these posts do not make the trick. In such a high-dimensional dataset I need something "less manual".

Any clue?

Thank you

like image 953
vog Avatar asked Dec 12 '25 03:12

vog


2 Answers

One options could be:

Reduce(`intersect`, original)

[1] "A" "B"
like image 172
tmfmnk Avatar answered Dec 14 '25 15:12

tmfmnk


Using purrr

library(purrr)
reduce(original, intersect)
#[1] "A" "B"
like image 35
akrun Avatar answered Dec 14 '25 16:12

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!