This may be the most inane question ever, but I'm having trouble understanding the function sapply: Here's the problem:

Example:

d stands for matrix (1:10, 5,2)

NA for d[3].

# [,1] [,2] [,3] [,4] [,5] [,6]

1 6 #[1,] #[1,] #[1,] #[1,] #

2 7 #[2,] #[2,] #[2,] #[2,] #

#[3,] NA #[3,] NA #[3,] NA #[3,]

##[4,] ##########################

#[5,] #[5,] #[5,] #[5,] #[5,

If I wanted to utilise the sapply function to calculate the row means, I'd do something like this:

sapply(d,mean)

#[1] NA 4 5 6 7 8 9 10 NA 4 5 6 7 8 9 10 NA 4 5 6 7 8 9 10 NA 4 5 6 7 8 9

Shouldn't it give me the average of the items' list? Instead of the mean, it just throws out the elements of my matrix.

I receive the correct response when I use apply:

apply(d,1,mean, na.rm=T, na.rm=T, na.rm=T, na.rm

[1] 3.5 4.5 8.0 6.5 7.5 7.5 7.5 7.5 7.5 7.5 7.5 7.5 7.5 7.5 7.5

Is anyone willing to explain themselves to me?
Jun 19, 2022 333 views

## 1 answer to this question.

Do you read 2? sapply. Either a vector or an expression object may be passed to the function. A matrix cannot be accepted. As a result, the matrix d in your example is treated as a vector of numbers:

sapply(as.numeric(d),mean)
• 3,040 points

## R function for finding the index of an element in a vector?

The function match works on vectors : x <- sample(1:10) x # ...READ MORE

+1 vote

## Which function can I use to clear the console in R and RStudio ?

Description                   Windows & Linux           Mac Clear console                      Ctrl+L ...READ MORE

## Why should I use set.seed function() in R?

set.seed(seed) Set the seed of R‘s random number ...READ MORE

## Python equivalent to replace function in R

There is actually a replace function in ...READ MORE

## How to add external markers in maps?

Use external markers by creating icons using ...READ MORE

## Add multiple maps over each other

How to multiple layers of maps over ...READ MORE

## Reduce markers overlapping in maps

Hey, You can either reduce the font size ...READ MORE

## How to create and call groups in maps?

Groups are used to group a set ...READ MORE

## why the predict() function does have different rows in R

Alter this sentence: model = lm(train\$latitude train\$crashes) to lm(crashes ...READ MORE