Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add label in table() in R

Tags:

r

I want to print 2*2 confusion matrix and label it. I am using table() in r.

Please click this to see the table

I want to add predicted and Reality label . Can anybody suggest me , how can I do it?

like image 471
jacob Avatar asked Feb 22 '18 01:02

jacob


People also ask

How do I add column labels in R?

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”,…..)

How do I add data to a table in R?

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.

How do I rename a column in a table in R?

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.

How do I display variable labels in R?

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.


1 Answers

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")))
like image 80
lefft Avatar answered Sep 21 '22 03:09

lefft