What is walk() Function in R

The walk() function is part of the purrr package in R that applies a function to each element of a list or vector, but unlike map(), it does not return anything.

The walk() function takes two arguments: a list and a function. The function is applied to each element of the list in turn, and the result is discarded. The main purpose of walk() is to operate on each list element, such as printing the element or modifying it in place without generating a new list.

Syntax

walk(.x, .f, ..., .progress = FALSE)

Parameters

.x: It is a list or atomic vector.

.f: It is a function.

...: Additional arguments passed on to the mapped function.

.progress: Whether to show a progress bar. Use TRUE to turn on a basic progress bar.

Example

library(purrr)

cars <- list("bmw", "audi", "mercedez")
walk(cars, print)

Output

[1] "bmw"
[1] "audi"
[1] "mercedez"

In this example, the walk() function applies the print() function to each element of the cars list, printing the element to the console. The result of walk() is NULL because the function does not return a value.

Difference between walk() and map() in R

The main difference between the walk() and map() functions is that walk() function is used when you want to act on each element of a list or vector, such as printing or writing to a file. Still, you don’t want to return anything. On the other hand, the map() function is used when you want to apply a function to each element of a list or vector and return the results as a new list or vector.

For example, if you have a list of numbers and want to square each number and return the results as a new list, you can use map() to apply the ^2 function to each number.

That’s it.

Leave a Comment