我的数据是广泛的形式,看起来像下面。数据包括名称和四个数据列。
df_wide <- data.frame(
name = c("John", "Smith", "Tom", "Alice"),
area = c("A", "A", "B", "B"),
hello_1 = c(20, 30, 40, 70),
hello_covered = c(60, 89, 76, 87),
world_1 = c(55, 65, 20, 29),
world_1_covered = c(87, 29, 43, 42)
)
字符串
我想把它转换成一个长格式,其中每个名称,我得到两行和两个数据列。我们期望的数据如下所示
name area medicine value covered
1 John A hello 20 60
2 John A world 55 87
3 Smith A hello 30 89
4 Smith A world 65 29
5 Tom B hello 40 76
6 Tom B world 20 43
7 Alice B hello 70 87
8 Alice B world 29 42
型
我试过使用pivto_longer
,但不太成功。
4条答案
按热度按时间qlfbtfca1#
您可以在
names_to
中设置".value"
,并提供names_sep
或names_pattern
之一,以指定如何拆分列名。字符串
cngwdvgl2#
可以先重命名以简化透视:
字符串
62lalag43#
tidyverse中的一种可选方法-不那么简洁,但可能更容易理解:
字符串
chhqkbe14#
一种方法应该适用于其他 hello_X/world_X 名称,因为这些名称标记了值。
mutate
medicine。字符串