I am trying to assign names to list of dimnnames using inputs from an function, but the names only output the function input name (i.e. if function(test1 = "abc)"
dimnames outputs "test1", not "abc"). An example function is here:
# example data
set.seed(123)
mcmr <- data.frame(type = rep(c("fm", "xp","mg"), each = 8),
teq = rep(c("string","ribbon"), 12),
value = sample(0:1, 24, replace = TRUE))
#example function
mcm_fun <- function(technique, test1, test2){
test1 <- mcmr[mcmr$type == test1 & mcmr$teq == technique, "value"]
test2 <- mcmr[mcmr$type == test2 & mcmr$teq == technique, "value"]
matrix(c(table(test1), table(test2)), nrow = 2,
dimnames = list(test1 = c("Positive", "Negative"), # want to name with test1 input
test2 = c("Positive", "Negative"))) # want to name with test2 input
}
Which outputs
mcm_fun("string", "mg", "xp")
# test2
#test1 Positive Negative
# Positive 1 3
# Negative 3 1
The desired output would include the function input for test1
and test2
:
# mg
#xp Positive Negative
# Positive 1 3
# Negative 3 1
I have tried assign()
and get()
but cant seem to get this to work and all I can seem to find is info on assigning the dimnames themselves.
CodePudding user response:
The labels you're asking about are the names
of the dimnames
of the table, so you can set them with:
names(dimnames(m)) <- nms
In your case, just add that assignment step into your function:
mcm_fun <- function(technique, t1, t2){
test1 <- mcmr[mcmr$type == t1 & mcmr$teq == technique, "value"]
test2 <- mcmr[mcmr$type == t2 & mcmr$teq == technique, "value"]
m <- matrix(c(table(test1), table(test2)), nrow = 2,
dimnames = list(test1 = c("Positive", "Negative"), # want to name with test1 input
test2 = c("Positive", "Negative"))) # want to name with test2 input
names(dimnames(m)) <- c(t1, t2)
return(m)
}
mcm_fun("string", "mg", "xp")
xp
mg Positive Negative
Positive 3 1
Negative 1 3
Note that I had to rename your arguments since you were overwriting them with the results of the test.
CodePudding user response:
The list
cannot evaluate the objects on the lhs of =
, we can use :=
with lst
(from dplyr
or purrr
)
library(purrr)
mcm_fun <- function(technique, test1, test2){
# assigned to a new object as the
# test1, test2 are assigned later to subset data
nm1 <- test1
nm2 <- test2
test1 <- mcmr[mcmr$type == test1 & mcmr$teq == technique, "value"]
test2 <- mcmr[mcmr$type == test2 & mcmr$teq == technique, "value"]
matrix(c(table(test1), table(test2)), nrow = 2,
dimnames = lst(!!nm1 := c("Positive", "Negative"), # want to name with test1 input
!!nm2 := c("Positive", "Negative"))) # want to name with test2 input
}
-testing
> mcm_fun("string", "mg", "xp")
xp
mg Positive Negative
Positive 3 1
Negative 1 3