dplyr`pivot_longer()`对象未找到,但是就在那里吗? [英] dplyr `pivot_longer()` object not found but it's right there?

查看:69
本文介绍了dplyr`pivot_longer()`对象未找到,但是就在那里吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

library(tidyverse)
df <- tibble(Date = as.Date(c("2020-01-01", "2020-01-02")),
             Shop = c("Store A", "Store B"),
             Employees = c(5, 10),
             Sales = c(1000, 3000))

#> # A tibble: 2 x 4
#>   Date       Shop    Employees Sales
#>   <date>     <chr>       <dbl> <dbl>
#> 1 2020-01-01 Store A         5  1000
#> 2 2020-01-02 Store B        10  3000

我正在按照 dplyr参考指南从dplyr传播/收集切换到ivot_ *.一个>.我想通过以下方式收集员工"和销售"列:

I'm switching from dplyr spread/gather to pivot_* following the dplyr reference guide. I want to gather the "Employees" and "Sales" columns in the following manner:

df %>% pivot_longer(-Date, -Shop, names_to = "Names", values_to = "Values")
#> Error in build_longer_spec(data, !!cols, names_to = names_to, 
#> values_to = values_to, : object 'Shop' not found

但是我遇到了这个错误.好像我在做正确的一切.除了我显然不是.你知道出了什么问题吗?

But I'm getting this error. It seems as though I'm doing everything right. Except that I'm apparently not. Do you know what went wrong?

推荐答案

cols 参数是要透视的所有列.您可以将其视为 reshape2 :: melt

The cols argument is all of the columns you want to pivot. You can think of it as the complement of the id.vars argument from reshape2::melt

df %>% pivot_longer(-c(Date, Shop), names_to = "Names", values_to = "Values")

与:

reshape2::melt(df, id.vars=c("Date", "Shop"), variable.name="Names", value.name="Value")

这篇关于dplyr`pivot_longer()`对象未找到,但是就在那里吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆