Using paste() to display output in R

Asked by At

Below is the code I have written, for some I am able to display output

data <- c(4,5,1,4,2,7,2,6,9,9,3)

#Mean
dt_mean = mean(data) 

#Median
dt_median = median(data)

#Mode
y <- table(data)
names(table(data))[table(data)==max(table(data))]

dt_mode <- names

#Output
cat("Mean: ", dt_mean)
cat("Median: ", dt_median)
paste(c("Mode: ", dt_mode))

I am getting output for Mean and Median in console correctly, but for Mode the below output is displayed:

{1] "Mode: "                ".Primitive(\"names\")"

As per the value of mode it have multiple values, what should I modify to get the output correctly?

Thanks!

2 Answers

0
mischva11 On

You forgot to assign your names from:

names(table(data))[table(data)==max(table(data))]  

just do

dt_mode <- names(table(data))[table(data)==max(table(data))] 

Explanation what happened in your case:

you printed names which is a function. When you write names in your console you get

function (x) .Primitive("names")

this return is, what got printed.

Full code:

data <- c(4,5,1,4,2,7,2,6,9,9,3)

#Mean
dt_mean = mean(data) 

#Median
dt_median = median(data)

#Mode

y <- table(data)
dt_mode <- names(table(data))[table(data)==max(table(data))]

#Output
cat("Mean: ", dt_mean)
cat("Median: ", dt_median)
paste(c("Mode: ", dt_mode))

Output:

cat("Mean: ", dt_mean)

Mean: 4.727273

cat("Median: ", dt_median)

Median: 4

paste(c("Mode: ", dt_mode))

[1] "Mode: " "2" "4" "9"

0
c1au61o_HH On

Yes, because you are assigning the primitive function name to dt_mode and you are not assigning names(table(data))[table(data)==max(table(data))] to anything.

If you want to get the mode you can use this function from here and then

getmode <- function(v) {
   uniqv <- unique(v)
   uniqv[which.max(tabulate(match(v, uniqv)))]
}

dt_mode <- getmode(data)

cat("Mode: ", dt_mode))