【问题标题】:mutate_each on tidyr nested table gives "Unknown inputs"tidyr 嵌套表上的 mutate_each 给出“未知输入”
【发布时间】:2016-07-22 21:41:40
【问题描述】:

我正在尝试对tidyr::nest 创建的一组表使用purr::map 执行mutate_each

以下是我正在尝试执行的操作以及由此产生的错误的示例:

library(tidyr)
library(gapminder)
library(dplyr)
library(purrr)


by_country <- gapminder %>% 
  group_by(continent, country) %>% 
  nest() %>% 
  mutate(data2 = map(data,  ~ mutate_each(.,funs(as.numeric))))

给予:

Error: Unknown inputs

是什么导致了这个问题?有解决办法吗?我可以使用apply 而不是mutate_each,但这会删除行名。

编辑:从第一个回复看来,目的还不清楚。所以也许我正试图以错误的方式做某事。让我解释一下。

如果你这样做:

by_country <- gapminder %>% 
   group_by(continent, country) %>% 
   nest()

你有:

by_country$data[[1]]
Source: local data frame [12 x 4]

    year lifeExp      pop gdpPercap
   (int)   (dbl)    (int)     (dbl)
1   1952  28.801  8425333  779.4453
2   1957  30.332  9240934  820.8530
3   1962  31.997 10267083  853.1007
4   1967  34.020 11537966  836.1971
5   1972  36.088 13079460  739.9811
6   1977  38.438 14880372  786.1134
7   1982  39.854 12881816  978.0114
8   1987  40.822 13867957  852.3959
9   1992  41.674 16317921  649.3414
10  1997  41.763 22227415  635.3414
11  2002  42.129 25268405  726.7341
12  2007  43.828 31889923  974.5803

我想要的是为每一列运行一个函数;但为每个嵌套表单独完成。所以我想在每张桌子上运行下面的等价物:

mutate_each(by_country$data[[1]],funs(as.numeric))

给予:

Source: local data frame [12 x 4]

    year lifeExp      pop gdpPercap
   (dbl)   (dbl)    (dbl)     (dbl)
1   1952  28.801  8425333  779.4453
2   1957  30.332  9240934  820.8530
3   1962  31.997 10267083  853.1007
4   1967  34.020 11537966  836.1971
5   1972  36.088 13079460  739.9811
6   1977  38.438 14880372  786.1134
7   1982  39.854 12881816  978.0114
8   1987  40.822 13867957  852.3959
9   1992  41.674 16317921  649.3414
10  1997  41.763 22227415  635.3414
11  2002  42.129 25268405  726.7341
12  2007  43.828 31889923  974.5803

【问题讨论】:

  • 你想达到什么目的?给定gapminder 数据框作为输入,也许显示预期的输出?
  • 好的。更新了问题。
  • 为什么不这样做:gapminder %&gt;% mutate_each_(funs(as.numeric), names(gapminder)[sapply(gapminder, is.integer)]) %&gt;% group_by(country, continent) %&gt;% nest()
  • 只是因为我需要在嵌套数据上运行 mutate_each。在示例中,这并不重要,但对于我正在尝试做的事情,它需要在嵌套数据上。我已经更改了每个嵌套表的形状,因此不能取消嵌套来执行 mutate_each。

标签: r dplyr tidyr purrr


【解决方案1】:

map 使用.x 在函数参数作为公式给出时引用输入数据。修改后,mutate_each 的形式有两种可能:

by_country <- gapminder %>% 
  group_by(continent, country) %>% 
  nest()  %>%
  mutate(data2 = map(data,  ~ mutate_each(.x, "as.numeric")))

by_country2 <- gapminder %>% 
  group_by(continent, country) %>% 
  nest()  %>%
  mutate(data2 = map(data,  ~ mutate_each(.x, funs(as.numeric(.)))))

似乎mutate(data2 = map(data, ~ mutate_each(.x, funs(as.numeric)))) 也应该可以工作,但它没有。

【讨论】:

  • 太棒了!非常感谢。
猜你喜欢
  • 2022-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-07
  • 2023-02-06
  • 2020-07-22
  • 2013-10-17
相关资源
最近更新 更多