#' @import data.table
.matrix_repeats <- function(m,value,use.line.names=TRUE) {
if(typeof(m)!=typeof(value)) {
stop("Error! Matrix and value should be of the same type.")
}
if(typeof(use.line.names)!="logical" | length(use.line.names)!=1) {
stop("Error! use.line.names should be a logical vector (TRUE or FALSE) of length 1.")
}
line.names <- list(rows=NULL,cols=NULL)
if(use.line.names==FALSE) {
line.names$rows <- seq_len(nrow(m))
line.names$cols <- seq_len(ncol(m))
} else {
if(is.null(rownames(m))) {
rownames(m) <- as.character(seq_len(nrow(m)))
line.names$rows <- rownames(m)
} else {
line.names$rows <- rownames(m)
}
if(is.null(colnames(m))) {
colnames(m) <- as.character(seq_len(ncol(m)))
line.names$cols <- colnames(m)
} else {
line.names$cols <- colnames(m)
}
}
total.repeats <-
mapply( # Apply over both the two orientations of the matrix (horizontal/vertical)
function(m,value,margin,orientation.tag) {
mapply( # Apply over EACH row or column (line) of matrix
function(line,line.names,value,orientation.tag) {
# Get the repeats in each line
line <- line |>
as.vector() |>
.vector_repeats(value=value)
# Write more information: name or number of column and orientation (horizontal/vertical)
line[,c("row.or.column.name","orientation"):=
.(line.names,orientation.tag)]
return(line)
},
line=asplit(m,margin),
line.names=line.names[[margin]],
SIMPLIFY=FALSE, # The SIMPLIFY=FALSE causes the result to be returned as a list
MoreArgs=list(value=value, # This MoreArgs list passes the non-iterated elements in the function
orientation.tag=orientation.tag)
) |> rbindlist() # Binds the repeats of each individual row or column
},
margin=c(1,2),
orientation.tag=as.factor(c("horizontal","vertical")),
SIMPLIFY=FALSE, # The SIMPLIFY=FALSE causes the result to be returned as a list
MoreArgs=list(m=m, # This MoreArgs list passes the non-iterated elements in the function
value=value)
) |> rbindlist() # Binds the repeats found in horizontal and vertical orientations
if(use.line.names==TRUE) {
total.repeats[,c("start","end"):=
.(fifelse(orientation=="horizontal",
line.names$cols[start],
line.names$rows[start]),
fifelse(orientation=="horizontal",
line.names$cols[end],
line.names$rows[end]))][]
}
return(total.repeats)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.