我有几个专栏
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))发布于 2021-03-18 19:34:23
这可以用pivot_longer轻松地完成,指定names_pattern提取值(.value)部分以进入列'Yes‘、'No’和另一个列'grp‘,该列提取列名的后缀部分。然后,可以使用column_to_rownames将“grp”列转换为行名。
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')-output
# 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))https://stackoverflow.com/questions/66697868
复制相似问题