简体   繁体   中英

Passing arguments to intersect / reduce function dynamically in R

I have a data frame that has several numeric columns. I want to create a loop that finds the length of the common elements of the data frame in the following way. Lets assume df is my data frame

 > df
  [,1] [,2] [,3] [,4]
  1    4    5    7
  2    1    4    8
  12   4    6    1
  4   12    1    9

The last element of my result vector should have the length of common elements in all the columns of df. The second last element should exclude the last column and take the length of common elements from column 1 to column n-1.

My result vector in this case should have c(3,2,1) The first element of result has 3 because 1,12 and 4 are common in column 1 & 2 The second element has 2 as 1 and 4 are common in column 1, column 2 and column 3 The third element has 1 as 1 is common in all the columns. Please assume that I have multiple such columns and rows.

I suppose we need a paste that can work dynamically inside a loop but i have not been able to get there yet. Please help. The following code gets the intersection of two columns.

 length(Reduce(intersect,  list(as.matrix(df[1]),as.matrix(df[2]))))                       

If this were a data.frame, your code is pretty close.

Reduce(intersect, df, accumulate=TRUE)
[[1]]
[1]  1  2 12  4

[[2]]
[1]  1 12  4

[[3]]
[1] 1 4

[[4]]
[1] 1

then drop the first element (which is the first column) and use lengths to calculate the lengths of each list element.

lengths(Reduce(intersect, df, accumulate=TRUE)[-1])
[1] 3 2 1

data

df <- 
structure(list(V1 = c(1L, 2L, 12L, 4L), V2 = c(4L, 1L, 4L, 12L
), V3 = c(5L, 4L, 6L, 1L), V4 = c(7L, 8L, 1L, 9L)), .Names = c("V1", 
"V2", "V3", "V4"), class = "data.frame", row.names = c(NA, -4L
))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM