R sapply() Function - List Apply with Simplified Output
The R sapply() function is similar to lapply(), but tries to simplify the returned list into a vector or matrix.
When the result returned by lapply() can be simplified into a simple structure, sapply() does so automatically.
The syntax of the sapply() function is as follows:
sapply(X, FUN, ..., simplify = TRUE)
Parameter Description:
-
X The input list or vector.
-
FUN The function to apply.
-
simplify Whether to try simplifying the result, TRUE by default.
Example
sapply vs lapply: compute means
scores
<-
list
(
Zhang San
=
c
(
88
,
90
,
85
)
,
Li Si
=
c
(
92
,
88
,
91
)
,
Wang Wu
=
c
(
76
,
82
,
78
)
)
lapply returns a list
result_list
<-
lapply
(
scores,
mean
)
(
"lapply result (list):"
)
(
result_list
)
sapply returns a vector
result_vec
<-
sapply
(
scores,
mean
)
(
"sapply result (vector):"
)
(
result_vec
)
sapply for statistics on data frame columns
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
)
)
)
(
"Multiple statistics:"
)
(
stat
)
The output of the code above is:
[1] "lapply 结果 (列表):"
$张三
[1] 87.66667
$李四
[1] 90.33333
$王五
[1] 78.66667
[1] "sapply 结果 (向量):"
张三 李四 王五
87.66667 90.33333 78.66667
[1] "多统计量:"
数学 英语 编程
均值 85.333 86.667 84.667
标准差 8.327 4.163 6.506
R Language Examples