ivot_wider()参数暗示Eroor的行数不同

时间:2020-09-14 22:15:27

标签: r data.table pivot tidyr

我有以下名为x的data.table对象:

 month.option   som.month
  all.year        56.6%
     diff        -0.9%

以及执行以下操作时:

x %>% pivot_wider(names_from = month.option, values_from = som.month) %>%
                select(diff, everything()) %>%
                set_names(c("Dif vs MA", "SOM YTD", "SOM AA"))

我收到以下错误:Error in data.frame(row = row_id, col = col_id) : arguments imply differing number of rows: 0, 2。但是由于x是2x2的data.table,所以我不明白原因。如果有人知道我看不到的可能的问题,我将不胜感激。

请注意,如果有任何有用的信息,则所有列的类型均为character

3 个答案:

答案 0 :(得分:1)

如果我们要使用pivot_wider,则可以通过将values_fn指定为I

来执行此操作而无需创建新列
library(dplyr)
library(tidyr)
x %>% 
  pivot_wider(names_from = month.option, values_from = som.month, values_fn =  I)
# A tibble: 1 x 2
#  all.year diff    
#  <I<chr>> <I<chr>>
#1 56.6%    -0.9%  

或者它也可以是获取first元素的函数

x %>% 
   pivot_wider(names_from = month.option, 
          values_from = som.month, values_fn =  first)
# A tibble: 1 x 2
#   all.year diff 
#  <chr>    <chr>
#1 56.6%    -0.9%

但是,transpose中的data.table可以轻松解决这类问题

data.table::transpose(x, make.names = 'month.option')
#  all.year  diff
#1    56.6% -0.9%

或者将deframeas_tibble_row一起使用会更直接

library(tibble)
deframe(x) %>%
   as_tibble_row
# A tibble: 1 x 2
#  all.year diff 
#  <chr>    <chr>
#1 56.6%    -0.9%

或者另一种选择是将第一列转换为行名,使用t进行转置,然后转换为tibble(或data.frame

x %>% 
    column_to_rownames('month.option') %>% 
     t %>%
     as_tibble
# A tibble: 1 x 2    
#   all.year diff 
#  <chr>    <chr>
#1 56.6%    -0.9%

数据

x <- structure(list(month.option = c("all.year", "diff"), som.month = c("56.6%", 
"-0.9%")), class = "data.frame", row.names = c(NA, -2L))

答案 1 :(得分:0)

使用相同的tidyverse尝试此pivot_wider()解决方案。您遇到了问题,因为该函数无法正确识别行。解决方案是创建ID:

#Code
df %>% mutate(id=1) %>%
 pivot_wider(names_from = month.option,values_from=som.month) %>%
select(-1)

输出:

# A tibble: 1 x 2
  all.year diff 
  <chr>    <chr>
1 56.6%    -0.9%

使用了一些数据:

#Data
df <- structure(list(month.option = c("all.year", "diff"), som.month = c("56.6%", 
"-0.9%")), class = "data.frame", row.names = c(NA, -2L))

答案 2 :(得分:0)

如果您有data.table,我们也可以使用dcast

library(data.table)
dcast(x, rowid(month.option)~month.option, value.var = 'som.month')

#   month.option all.year  diff
#1:            1    56.6% -0.9%