ACLAN
ACLAN

Reputation: 401

From integers to a data.frame (without losing the structure) in R

I'm trying to write a function in which:

  1. I get the rows and columns numbers where I have x=="pos" using the following code

    col.numbers <- which(change.matrix2 =="pos", arr.ind=TRUE)
    

    I'm using this code within a function so the change.matrix2 has the exact same structure and it's always a data frame.

  2. I noticed that I get col.numbers with different structures and I don't know why.

Here is what I get:

Example 1:

 > col.numbersA
row col 
  1   8 

> str(col.numbersA)
 Named int [1:2] 1 8
 - attr(*, "names")= chr [1:2] "row" "col"

> is.integer(col.numbersA)
[1] TRUE

and I want to convert it to a data frame with the same structure so I use

> as.data.frame(t(col.numbersA))
  row col
1   1   8

and it works!

Example 2:

> col.numbersB
   row col
10   1  10
4    2  15
11   3  10
3    4  15
5    5  40
5    5  41
12   6  10
1    7   3
6    8  40
7    9  43
9   10  44
2   11   3
8   12  43

> str(col.numbersB)
 int [1:13, 1:2] 1 2 3 4 5 5 6 7 8 9 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:13] "10" "4" "11" "3" ...
  ..$ : chr [1:2] "row" "col"

> is.integer(col.numbersB)
[1] TRUE

but when I use the same code as in Example 1 to convert it to a data frame, I get this:

> as.data.frame(t(col.numbersB))
    10  4 11  3  5  5 12 1  6  7  9  2  8
row  1  2  3  4  5  5  6 7  8  9 10 11 12
col 10 15 10 15 40 41 10 3 40 43 44  3 43

but I would like to keep the structure of col.numersB, i.e. the transpose of this.

Does anyone know how to code from integer to data.frame without losing the structure (or dimensions) of col.numbers?

Upvotes: 1

Views: 81

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

col.numbersA appears to be a named vector, while col.numbersB is a matrix.

You can check for dimensions before deciding whether to transpose or not. As a simple function, you can try something like:

myfun <- function(input) {
  if (is.null(dim(input))) as.data.frame(t(input)) else as.data.frame(input)
}

Example:

set.seed(1)
M <- matrix(c(12, sample(5, 24, TRUE)), ncol = 5)
M
A <- setNames(c(1L, 2L), c("row", "col"))
B <- which(M == 4, arr.ind = TRUE)

myfun(A)
myfun(B)

You may want to try to figure out how you're ending up with a named vector rather than a one-row matrix for a single match though. The following gives me a one-row matrix, not a named vector, like you show. And arr.ind should always do that....

which(M == 12, arr.ind = TRUE)

Upvotes: 1

Related Questions