Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R lapply() Function - Applying a Function to a List

R lapply() Function - Applying a Function to a List

R Language Examples R Language Examples

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:

Example

Compute the mean for each element of 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

(

"Means of each group:"

)

print

(

result

)

Compute the range for each column of a 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

(

"Ranges of each column:"

)

print

(

result2

)

The output of the code above is:

[1] "各组的均值:"

$group1

[1] 88.4



$group2

[1] 74.2



$group3

[1] 91.4



[1] "各列的范围:"

$数学

[1] 76 92



$英语

[1] 82 90



$编程

[1] 78 91

R Language Examples R Language Examples