R Func Lapply
# R lapply() Function - List Apply
[ R Language Examples](#)
The R lapply() function applies 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 lapply() function syntax format is as follows:
lapply(X, FUN, ...)
**Parameter Description:**
* **X** Input list or vector.
* **FUN** The function to apply.
* **...** Additional arguments passed to FUN.
## Examples
# 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)
Executing the above code outputs the following result:
"Mean of each group:" $group1 88.4 $group2 74.2 $group3 91.4 "Range of each column:" $Math 76 92 $English 82 90 $Programming 78 91
[ R Language Examples](#)
YouTip