Pivotting multiple columns with literal names_pattern [duplicate]

我与影子孤独终老i 提交于 2020-01-24 19:44:11

问题


I want to pivot_longer() my data frame to contain a column with the row number of the original data. Consider the following data frame:

set.seed(0)

df <- data.frame(
  a = runif(3),
  b = runif(3),
  c = runif(3)
) %>% mutate("row_id" = row_number())


> df
          a         b         c row_id
1 0.8966972 0.5728534 0.8983897      1
2 0.2655087 0.9082078 0.9446753      2
3 0.3721239 0.2016819 0.6607978      3

The desired output should look like this:

   name   value  row_id
   <chr>  <dbl>  <int>
 1 a      0.897  1
 2 b      0.573  1
 3 c      0.898  1
 4 a      0.266  2
 5 b      0.908  2
 6 c      0.945  2
 7 a      0.372  3
 8 b      0.202  3
 9 c      0.661  3

After reading ?pivot_longer I tried to accomplish this by specifying names_pattern and names_to in the following way:

result <- df %>% tidyr::pivot_longer(
  cols = everything(),
  names_to = c(".value", "row_id"),
  names_pattern = "(.)([row_id])"
)

But end up with an output I don't really understand:

# A tibble: 6 x 2
  row_id     r
  <chr>  <int>
1 NA        NA
2 o          1
3 NA        NA
4 o          2
5 NA        NA
6 o          3

I thought [row_id] should define a column by it's literal name. What am I doing wrong? Thanks


回答1:


We don't need to specify the pattern here. Just use the cols to select or deselect (-). In this case, it makes more sense to deselect the 'row_id'

library(dplyr)
library(tidyr)
df %>% 
   pivot_longer(cols = -row_id)

It can also be written as

df %>% 
    pivot_longer(cols = a:c)

Or a regex pattern as name with matches or some of the select_helpers

df %>%
   pivot_longer(cols= matches('^[a-c]$'))


来源:https://stackoverflow.com/questions/59238525/pivotting-multiple-columns-with-literal-names-pattern

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