Using map with a vector of data table names and utils::data

…衆ロ難τιáo~ 提交于 2021-02-10 09:41:33

问题


I would like to load two datasets from the mlbench package into my environment. I know that I am able to do so manually using the data(x) function, but I would like to do this using purrr:map. However, when I try to do this I keep getting the following error:

data set ‘.x’ not founddata set ‘.x’ not found[[1]]
[1] ".x"

[[2]]
[1] ".x"

Is this possible?

## libraries
library("mlbench")
library("dplyr")
library("purrr")

## load data sets into environment manually
data(BostonHousing)
data(BostonHousing2)

## load data sets into environment using map
data_names <- c("BostonHousing", "BostonHousing2")

## generates error
data_names %>% map(~data(.x))

回答1:


With data, there are two parameters for loading the data, the ... checks for literal values and list for a vector of character strings. All, we have to do is instead of the default option of ..., specify list to load the datasets from the string vector and then use mget to load those datasets in a list

library(dplyr)
library(purrr)
library(mlbench)
data(list = data_names)
mget(data_names)  %>%
     map(head, 5)

-output

#$BostonHousing
#     crim zn indus chas   nox    rm  age    dis rad tax ptratio      b lstat medv
#1 0.00632 18  2.31    0 0.538 6.575 65.2 4.0900   1 296    15.3 396.90  4.98 24.0
#2 0.02731  0  7.07    0 0.469 6.421 78.9 4.9671   2 242    17.8 396.90  9.14 21.6
#3 0.02729  0  7.07    0 0.469 7.185 61.1 4.9671   2 242    17.8 392.83  4.03 34.7
#4 0.03237  0  2.18    0 0.458 6.998 45.8 6.0622   3 222    18.7 394.63  2.94 33.4
#5 0.06905  0  2.18    0 0.458 7.147 54.2 6.0622   3 222    18.7 396.90  5.33 36.2

#$BostonHousing2
#        town tract     lon     lat medv cmedv    crim zn indus chas   nox    rm  age    dis rad tax ptratio      b lstat
#1     Nahant  2011 -70.955 42.2550 24.0  24.0 0.00632 18  2.31    0 0.538 6.575 65.2 4.0900   1 296    15.3 396.90  4.98
#2 Swampscott  2021 -70.950 42.2875 21.6  21.6 0.02731  0  7.07    0 0.469 6.421 78.9 4.9671   2 242    17.8 396.90  9.14
#3 Swampscott  2022 -70.936 42.2830 34.7  34.7 0.02729  0  7.07    0 0.469 7.185 61.1 4.9671   2 242    17.8 392.83  4.03
#4 Marblehead  2031 -70.928 42.2930 33.4  33.4 0.03237  0  2.18    0 0.458 6.998 45.8 6.0622   3 222    18.7 394.63  2.94
#5 Marblehead  2032 -70.922 42.2980 36.2  36.2 0.06905  0  2.18    0 0.458 7.147 54.2 6.0622   3 222    18.7 396.90  5.33


来源:https://stackoverflow.com/questions/64744192/using-map-with-a-vector-of-data-table-names-and-utilsdata

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!