1

我有几列

 Location|Yes M & M Peanuts| No M& M Peanuts | Yes M & M Almond| No M& M Almond|Location
               5                 10                 20             6                 NYC

我想使用表函数或更方便的方法将这些列转换为

              Yes | No
M & M Peanuts  5    10
M & M Almond   20    6        

更新示例

df2 <- structure(list(`Yes M & M Peanuts` = 5L, `No M & M Peanuts` = 10L, 
                      `Yes M & M Almond` = 20L, `No M & M Almond` = 6L, "Location" = "NYC"), class = "data.frame", 
                 row.names = c(NA, 
                               -1L))
4

1 回答 1

2

这可以很容易地完成pivot_longer,指定names_pattern提取值 ( .value) 部分以进入列“是”、“否”和另一列“grp”,该列提取列名的后缀部分。然后,可以将“grp”列转换为行名column_to_rownames

library(dplyr)
library(tidyr)
library(tibble)
df1 %>% 
  pivot_longer(cols = everything(), names_to = c(".value", "grp"),
        names_pattern = "(Yes|No)\\s*(.*)") %>%
  column_to_rownames('grp')

-输出

#               Yes No
#M & M Peanuts   5 10
#M & M Almond   20  6

在更新的帖子中使用 OP 的第二个数据集,我们需要指定cols不带“位置”的

df2 %>% 
  pivot_longer(cols = -Location, names_to = c(".value", "grp"),
    names_pattern = "(Yes|No)\\s*(.*)") %>%
  column_to_rownames('grp')
#              Location Yes No
#M & M Peanuts      NYC   5 10
#M & M Almond       NYC  20  6

数据

df1 <- structure(list(`Yes M & M Peanuts` = 5L, `No M & M Peanuts` = 10L, 
    `Yes M & M Almond` = 20L, `No M & M Almond` = 6L), class = "data.frame", 
    row.names = c(NA, 
-1L))
于 2021-03-18T19:34:23.617 回答