R Func Sapply
# R sapply() Function - List Application with Simplified Output
[ R Language Examples](#)
The R sapply() function is similar to lapply(), but it attempts to simplify the returned list into a vector or matrix.
When the result returned by lapply() can be simplified into a simpler structure, sapply() will automatically do so.
The syntax of the sapply() function is as follows:
sapply(X, FUN, ..., simplify = TRUE)
**Parameter Description:**
* **X** Input list or vector.
* **FUN** The function to apply.
* **simplify** Whether to attempt to simplify the result, default is TRUE.
## Example
```r
# sapply vs lapply: Calculate Mean
scores <-list(
Zhang San =c(88, 90, 85),
Li Si =c(92, 88, 91),
Wang Wu =c(76, 82, 78)
)
# lapply Returns Lists
result_list <-lapply(scores, mean)
print("lapply Result (Lists):")
print(result_list)
# sapply Returns vector
result_vec <-sapply(scores, mean)
print("sapply Result (vector):")
print(result_vec)
# sapply Used for column-wise statistics in data frames
df<-data.frame(Math =c(88, 92, 76),
English =c(90, 88, 82),
programming =c(85, 91, 78))
stat <-sapply(df, function(x)c(Mean =mean(x),
Standard Deviation =sd(x)))
print("Multiple statistics:")
print(stat)
Executing the above code outputs the following result:
```text
"lapply Result (Lists):" $Zhang San 87.66667 $Li Si 90.33333 $Wang Wu 78.66667 "sapply Result (vector):" Zhang San Li Si Wang Wu87.66667 90.33333 78.66667 "Multiple statistics:" Math English programmingMean 85.333 86.667 84.667Standard Deviation 8.327 4.163 6.506
[ R Language Examples](#)
YouTip