map function - RDocumentation (2024)

Description

The map functions transform their input by applying a function toeach element of a list or atomic vector and returning an object ofthe same length as the input.

  • map() always returns a list. See the modify() family forversions that return an object of the same type as the input.

  • map_lgl(), map_int(), map_dbl() and map_chr() return anatomic vector of the indicated type (or die trying). For these functions,.f must return a length-1 vector of the appropriate type.

  • map_vec() simplifies to the common type of the output. It works withmost types of simple vectors like Date, POSIXct, factors, etc.

  • walk() calls .f for its side-effect and returnsthe input .x.

Usage

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

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

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

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

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

map_vec(.x, .f, ..., .ptype = NULL, .progress = FALSE)

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

Value

The output length is determined by the length of the input.The output names are determined by the input names.The output type is determined by the suffix:

  • No suffix: a list; .f() can return anything.

  • _lgl(), _int(), _dbl(), _chr() return a logical, integer, double,or character vector respectively; .f() must return a compatible atomicvector of length 1.

  • _vec() return an atomic or S3 vector, the same type that .f returns..f can return pretty much any type of vector, as long as its length 1.

  • walk() returns the input .x (invisibly). This makes it easy touse in a pipe. The return value of .f() is ignored.

Any errors thrown by .f will be wrapped in an error with classpurrr_error_indexed.

Arguments

.x

A list or atomic vector.

.f

A function, specified in one of the following ways:

  • A named function, e.g. mean.

  • An anonymous function, e.g. \(x) x + 1 or function(x) x + 1.

  • A formula, e.g. ~ .x + 1. You must use .x to refer to the firstargument. Only recommended if you require backward compatibility witholder versions of R.

  • A string, integer, or list, e.g. "idx", 1, or list("idx", 1) whichare shorthand for \(x) pluck(x, "idx"), \(x) pluck(x, 1), and\(x) pluck(x, "idx", 1) respectively. Optionally supply .default toset a default value if the indexed element is NULL or does not exist.

...

Additional arguments passed on to the mapped function.

We now generally recommend against using ... to pass additional(constant) arguments to .f. Instead use a shorthand anonymous function:

# Instead ofx |> map(f, 1, 2, collapse = ",")# do:x |> map(\(x) f(x, 1, 2, collapse = ","))

This makes it easier to understand which arguments belong to whichfunction and will tend to yield better error messages.

.progress

Whether to show a progress bar. Use TRUE to turn ona basic progress bar, use a string to give it a name, or seeprogress_bars for more details.

.ptype

If NULL, the default, the output type is the common typeof the elements of the result. Otherwise, supply a "prototype" givingthe desired type of output.

See Also

map_if() for applying a function to only those elementsof .x that meet a specified condition.

Other map variants: imap(),lmap(),map2(),map_depth(),map_if(),modify(),pmap()

Examples

Run this code

# Compute normal distributions from an atomic vector1:10 |> map(rnorm, n = 10)# You can also use an anonymous function1:10 |> map(\(x) rnorm(10, x))# Simplify output to a vector instead of a list by computing the mean of the distributions1:10 |> map(rnorm, n = 10) |> # output a list map_dbl(mean) # output an atomic vector# Using set_names() with character vectors is handy to keep track# of the original inputs:set_names(c("foo", "bar")) |> map_chr(paste0, ":suffix")# Working with listsfavorite_desserts <- list(Sophia = "banana bread", Eliott = "pancakes", Karina = "chocolate cake")favorite_desserts |> map_chr(\(food) paste(food, "rocks!"))# Extract by name or position# .default specifies value for elements that are missing or NULLl1 <- list(list(a = 1L), list(a = NULL, b = 2L), list(b = 3L))l1 |> map("a", .default = "???")l1 |> map_int("b", .default = NA)l1 |> map_int(2, .default = NA)# Supply multiple values to index deeply into a listl2 <- list( list(num = 1:3, letters[1:3]), list(num = 101:103, letters[4:6]), list())l2 |> map(c(2, 2))# Use a list to build an extractor that mixes numeric indices and names,# and .default to provide a default value if the element does not existl2 |> map(list("num", 3))l2 |> map_int(list("num", 3), .default = NA)# Working with data frames# Use map_lgl(), map_dbl(), etc to return a vector instead of a list:mtcars |> map_dbl(sum)# A more realistic example: split a data frame into pieces, fit a# model to each piece, summarise and extract R^2mtcars |> split(mtcars$cyl) |> map(\(df) lm(mpg ~ wt, data = df)) |> map(summary) |> map_dbl("r.squared")

Run the code above in your browser using DataLab

map function - RDocumentation (2024)
Top Articles
13 arrested after pro-Palestinian students barricade themselves inside Stanford University president’s office
Family calls for justice after neighbor arrested in killing of mom of 4 in front of her children
WALB Locker Room Report Week 5 2024
Pollen Count Centreville Va
NOAA: National Oceanic &amp; Atmospheric Administration hiring NOAA Commissioned Officer: Inter-Service Transfer in Spokane Valley, WA | LinkedIn
Radikale Landküche am Landgut Schönwalde
What Are Romance Scams and How to Avoid Them
123 Movies Black Adam
Lamb Funeral Home Obituaries Columbus Ga
Midflorida Overnight Payoff Address
Achivr Visb Verizon
Craigslist Labor Gigs Albuquerque
Sitcoms Online Message Board
Vichatter Gifs
Günstige Angebote online shoppen - QVC.de
California Department of Public Health
2021 Lexus IS for sale - Richardson, TX - craigslist
Pac Man Deviantart
Download Center | Habasit
Log in or sign up to view
Vintage Stock Edmond Ok
Rimworld Prison Break
[PDF] NAVY RESERVE PERSONNEL MANUAL - Free Download PDF
Okc Body Rub
27 Paul Rudd Memes to Get You Through the Week
104 Presidential Ct Lafayette La 70503
Pioneer Library Overdrive
Speedstepper
Is Light Raid Hard
13301 South Orange Blossom Trail
Fuse Box Diagram Honda Accord (2013-2017)
Marlene2995 Pagina Azul
Mchoul Funeral Home Of Fishkill Inc. Services
Insidious 5 Showtimes Near Cinemark Southland Center And Xd
Rust Belt Revival Auctions
LEGO Star Wars: Rebuild the Galaxy Review - Latest Animated Special Brings Loads of Fun With An Emotional Twist
Spinning Gold Showtimes Near Emagine Birch Run
Afspraak inzien
Caderno 2 Aulas Medicina - Matemática
Google Chrome-webbrowser
Best Restaurant In Glendale Az
Evil Dead Rise (2023) | Film, Trailer, Kritik
Sam's Club Gas Prices Florence Sc
9 oplossingen voor het laptoptouchpad dat niet werkt in Windows - TWCB (NL)
Craigslist Boats Dallas
California Craigslist Cars For Sale By Owner
Atu Bookstore Ozark
Embry Riddle Prescott Academic Calendar
bot .com Project by super soph
Cars & Trucks near Old Forge, PA - craigslist
Competitive Comparison
Escape From Tarkov Supply Plans Therapist Quest Guide
Latest Posts
Article information

Author: Ouida Strosin DO

Last Updated:

Views: 5441

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Ouida Strosin DO

Birthday: 1995-04-27

Address: Suite 927 930 Kilback Radial, Candidaville, TN 87795

Phone: +8561498978366

Job: Legacy Manufacturing Specialist

Hobby: Singing, Mountain biking, Water sports, Water sports, Taxidermy, Polo, Pet

Introduction: My name is Ouida Strosin DO, I am a precious, combative, spotless, modern, spotless, beautiful, precious person who loves writing and wants to share my knowledge and understanding with you.