R lapply() Function - List Apply
The R lapply() function is used to apply a function to each element of a list or vector, returning a list.
lapply() is one of the most important functional programming tools in R, avoiding the use of for loops.
The syntax of the lapply() function is as follows:
lapply(X, FUN, ...)
Parameter description:
XInput list or vector.
FUNThe function to apply.
...Additional arguments to pass to FUN.
Example
# Calculate the mean for each element in the list
list_data <- list(
group1 = c(85, 88, 90, 87, 92),
group2 = c(72, 75, 78, 70, 76),
group3 = c(90, 93, 88, 95, 91)
)
result <- lapply(list_data, mean)
print("Mean of each group:")
print(result)
# Calculate the range for each column of the data frame
df <- data.frame(
Math= c(88, 92, 76),
English= c(90, 88, 82),
Programming= c(85, 91, 78)
)
result2 <- lapply(df, range)
print("Range of each column:")
print(result2)
list_data <- list(
group1 = c(85, 88, 90, 87, 92),
group2 = c(72, 75, 78, 70, 76),
group3 = c(90, 93, 88, 95, 91)
)
result <- lapply(list_data, mean)
print("Mean of each group:")
print(result)
# Calculate the range for each column of the data frame
df <- data.frame(
Math= c(88, 92, 76),
English= c(90, 88, 82),
Programming= c(85, 91, 78)
)
result2 <- lapply(df, range)
print("Range of each column:")
print(result2)
Executing the above code produces the following output:
[1] "各组的均值:" $group1 [1] 88.4 $group2 [1] 74.2 $group3 [1] 91.4 [1] "各列的范围:" $数学 [1] 76 92 $英语 [1] 82 90 $编程 [1] 78 91Other Extensions
R Language Examples