我有以下名为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
答案 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%
或者将deframe
与as_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%