R sapply() function - List application with simplified output
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 to a simple structure, sapply() will do so automatically.
The syntax of the sapply() function is as follows:
sapply(X, FUN, ..., simplify = TRUE)
Parameter description:
XInput list or vector.
FUNThe function to be applied.
simplifyWhether to attempt to simplify the result, default TRUE.
Example
# sapply vs lapply: compute mean
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)
print("lapply result (list):")
print(result_list)
# sapply returns a vector
result_vec <- sapply(scores, mean)
print("sapply result (vector):")
print(result_vec)
# sapply used for statistics of each column in data frame
df <- data.frame(Mathematics= 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)
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)
print("lapply result (list):")
print(result_list)
# sapply returns a vector
result_vec <- sapply(scores, mean)
print("sapply result (vector):")
print(result_vec)
# sapply used for statistics of each column in data frame
df <- data.frame(Mathematics= 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)
The output after running the above code 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
Other extensions
R language example