问题描述
我有几列
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))
解决方法
这可以通过 pivot_longer
轻松完成,指定 names_pattern
以提取值 (.value
) 部分以进入列“是”、“否”和另一列“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_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))