I have two tibbles and I am trying to apply the glimpse() function to each tibble. It can be done easily using for loops. But I am wondering how to do it using map() or other similar functions.
df1 <- tibble(A = c(1,1,1), B = c(2,2,2))
df2 <- tibble(C = c(3,3,3), D = c(4,4,4))
dfs = list(df1, df2)
I want this:
for (df in dfs) {
glimpse(df)
}
# Rows: 3
# Columns: 2
# $ A <dbl> 1, 1, 1
# $ B <dbl> 2, 2, 2
# Rows: 3
# Columns: 2
# $ C <dbl> 3, 3, 3
# $ D <dbl> 4, 4, 4
But map does this:
map(dfs, glimpse)
# Rows: 3
# Columns: 2
# $ A <dbl> 1, 1, 1
# $ B <dbl> 2, 2, 2
# Rows: 3
# Columns: 2
# $ C <dbl> 3, 3, 3
# $ D <dbl> 4, 4, 4
# [[1]]
# # A tibble: 3 × 2
# A B
# <dbl> <dbl>
# 1 1 2
# 2 1 2
# 3 1 2
#
# [[2]]
# # A tibble: 3 × 2
# C D
# <dbl> <dbl>
# 1 3 4
# 2 3 4
# 3 3 4
CodePudding user response:
map()
always returns a list, even if the applied function returns silently or NULL
. walk()
is like map()
but only executes the supplied function for side effects:
library(tidyverse)
df1 <- tibble(A = c(1,1,1), B = c(2,2,2))
df2 <- tibble(C = c(3,3,3), D = c(4,4,4))
dfs = list(df1, df2)
walk(dfs, glimpse)
#> Rows: 3
#> Columns: 2
#> $ A <dbl> 1, 1, 1
#> $ B <dbl> 2, 2, 2
#> Rows: 3
#> Columns: 2
#> $ C <dbl> 3, 3, 3
#> $ D <dbl> 4, 4, 4
Created on 2022-07-31 by the reprex package (v2.0.1)
CodePudding user response:
Why not
library(dplyr)
dfs %>%
glimpse()
List of 2
$ : tibble [3 x 2] (S3: tbl_df/tbl/data.frame)
..$ A: num [1:3] 1 1 1
..$ B: num [1:3] 2 2 2
$ : tibble [3 x 2] (S3: tbl_df/tbl/data.frame)
..$ C: num [1:3] 3 3 3
..$ D: num [1:3] 4 4 4