Home > Software design >  Extracting named data frame indices into a 2 column array based on condition in R
Extracting named data frame indices into a 2 column array based on condition in R

Time:10-28

I am trying to extract row and column name combinations from a data frame that is equal to 2 and plug these into a 2x9 data frame. With the first column having the row names and the second column having the column names of the data frame.

This is a smaller scale example of the data frame(DF):

A B C
A 5 2 1
B 8 4 2
C 2 8 1

And I want to fill in an empty 2x9 data frame(SD) like this:

RowNames ColumnNames
NA NA
NA NA
C A
A B
NA NA
NA NA
NA NA
B C
NA NA

I am using the following code (with k being the conundrum I am dealing with) :

DF <- data.frame(A <- c(5, 8, 2),
                B <- c(2, 4, 8),
                C <- c(1, 2, 1), 
                row.names = c("A", "B", "C"))

SD <- data.frame(RowNames = c(rep(NA,9)),
                ColumnNames = c(rep(NA,9)))

for(i in 1:nrow(DF)) {
  for(j in 1:ncol(DF)) {
    ifelse(DF[i,j] == 2, SD[k,1] <- rownames(DF[i,]), SD[k,1] <- NA )
    ifelse(DF[i,j] == 2, SD[k,2] <- colnames(DF[,j]), SD[k,2] <- NA )
  }
} 

Problem: I cannot think of a formula using i and j that allows for k to run from 1 to 9 within the loop.

I have only been coding for a few months, so excuse me if I am missing anything here.

CodePudding user response:

In addition to this comment:

Try k <- i (ncol(DF)*(j-1)) or k <- j (nrow(DF)*(i-1)) depending on whether it is row-wise or column-wise.

Subset the row names instead of the table.

DF <- data.frame(A = c(5, 8, 2),
                 B = c(2, 4, 8),
                 C = c(1, 2, 1), 
                 row.names = c("A", "B", "C"))

SD <- data.frame(RowNames = c(rep(NA,9)),
                 ColumnNames = c(rep(NA,9)))

for(i in 1:nrow(DF)) {
  for(j in 1:ncol(DF)) {
    k <- i   (ncol(DF)*(j-1))
    SD[k,1] <- ifelse(DF[i,j] == 2, rownames(DF)[i], NA)
    SD[k,2] <- ifelse(DF[i,j] == 2, rownames(DF)[j], NA)
  }
} 

SD
  RowNames ColumnNames
1     <NA>        <NA>
2     <NA>        <NA>
3        C           A
4        A           B
5     <NA>        <NA>
6     <NA>        <NA>
7     <NA>        <NA>
8        B           C
9     <NA>        <NA>
  • Related