Dhrubojyoti Sinha
Dhrubojyoti Sinha

Reputation: 25

Refer to column name and row name within an apply statement in R

I have a dataframe in R which looks like the one below.

    a b c d e f
    0 1 1 0 0 0
    1 1 1 1 0 1
    0 0 0 1 0 1
    1 0 0 1 0 1
    1 1 1 0 0 0

The database is big, spanning over 100 columns and 5000 rows and contain all binaries (0's and 1's). I want to construct an overlap between each and every columns in R. Something like the one given below. This overlap dataframe will be a square matrix with equal number of rows and columns and that will be same as the number of columns in the 1st dataframe.

      a b c d e f
    a 3 2 2 2 0 2
    b 2 3 3 3 0 1
    c 2 3 3 1 0 1
    d 2 3 1 3 0 3
    e 0 0 0 0 0 0
    f 2 1 1 3 0 3

Each cell of the second dataframe is populated by the number of cases where both row and column have 1 in the first dataframe.

I'm thinking of constructing a empty matrix like this:

    df <- matrix(ncol = ncol(data), nrow = ncol(data))
    colnames(df) <- names(data)
    rownames(df) <- names(data)

.. and iterating over each cell of this matrix using an apply command reading the corresponding row name (say, x) and column name (say, y) and running a function like the one below.

    summation <- function (x,y) (return (sum(data$x * data$y)))

The problem with is I can't find out the row name and column name while within an apply function. Any help will be appreciated.

Any more efficient way than what I'm thinking is more than welcome.

Upvotes: 1

Views: 238

Answers (1)

markus
markus

Reputation: 26343

You are looking for crossprod

crossprod(as.matrix(df1))
#  a b c d e f
#a 3 2 2 2 0 2
#b 2 3 3 1 0 1
#c 2 3 3 1 0 1
#d 2 1 1 3 0 3
#e 0 0 0 0 0 0
#f 2 1 1 3 0 3

data

df1 <- structure(list(a = c(0L, 1L, 0L, 1L, 1L), b = c(1L, 1L, 0L, 0L, 
1L), c = c(1L, 1L, 0L, 0L, 1L), d = c(0L, 1L, 1L, 1L, 0L), e = c(0L, 
0L, 0L, 0L, 0L), f = c(0L, 1L, 1L, 1L, 0L)), .Names = c("a", 
"b", "c", "d", "e", "f"), class = "data.frame", row.names = c(NA, 
-5L))

Upvotes: 1

Related Questions