I want to print 2*2 confusion matrix and label it. I am using table()
in r.
I want to add predicted and Reality label . Can anybody suggest me , how can I do it?
Method 1: Using colnames() function colnames() function in R is used to set headers or names to columns of a dataframe or matrix. Syntax: colnames(dataframe) <- c(“col_name-1”, “col_name-2”, “col_name-3”, “col_name-4”,…..)
To add or insert observation/row to an existing Data Frame in R, we use rbind() function. We can add single or multiple observations/rows to a Data Frame in R using rbind() function.
Rename Column using colnames() colnames() is the method available in R base which is used to rename columns/variables present in the data frame. By using this you can rename a column by index and name. Alternatively, you can also use name() method.
To get the variable label, simply call var_label() . To remove a variable label, use NULL . In RStudio, variable labels will be displayed in data viewer.
This is a similar problem to the one in this question. You can follow that approach,
but simplify things a bit by just using a matrix to hold the values, and
just setting its dimension names to "predicted"
and "observed"
:
# create some fake data (2x2, since we're building a confusion matrix)
dat <- matrix(data=runif(n=4, min=0, max=1), nrow=2, ncol=2,
dimnames=list(c("pos", "neg"), c("pos", "neg")))
# now set the names *of the dimensions* (not the row/colnames)
names(dimnames(dat)) <- c("predicted", "observed")
# and we get what we wanted
dat
# output:
# observed
# predicted pos neg
# pos 0.8736425 0.7987779
# neg 0.2402080 0.6388741
Update: @thelatemail made the nice point in the comments that you can specify dimension names when creating tables. The same is true of matrices, except you supply them as names of the dimnames
list elements when calling matrix()
. So here's an even more compact way:
matrix(data=runif(n=4, min=0, max=1), nrow=2, ncol=2,
dimnames=list(predicted=c("pos", "neg"), observed=c("pos", "neg")))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With