使用唯一 ID 重塑数据框,并根据相应的值将行转为列
Reshape the dataframe using unique ID and transpose the row to column based on the corresponding value
我有一个如下所示的数据框
Sample ID
Parameter
Value
Unit
1
apple
30
g
1
pear
15
lb
1
organge
20
kg
2
apple
2
g
2
pear
3
lb
2
orange
10
kg
3
apple
15
g
3
pear
23
lb
3
orange
12
kg
我想根据样本ID进行转置,把对应的值放到列中
Sample ID
apple_value_unit(g)
pear_value_unit(lb)
orange_value_unit(kg)
1
30
15
20
2
2
3
10
3
15
23
12
有什么方法可以转置和匹配值吗?我尝试了 cast(),但它无法将值映射到相应的参数。
在使用 pivot_wider
重塑为 'wide' 格式之前,我们可以将 'Parameter' 和 'Unit' 列连接成一个列
library(dplyr)
library(stringr)
library(tidyr)
df1 %>%
mutate(Parameter = sprintf('%s_value_unit(%s)', Parameter, Unit),
.keep = "unused") %>%
pivot_wider(names_from = Parameter, values_from = Value)
-输出
# A tibble: 3 × 4
SampleID `apple_value_unit(g)` `pear_value_unit(lb)` `orange_value_unit(kg)`
<int> <int> <int> <int>
1 1 30 15 20
2 2 2 3 10
3 3 15 23 12
数据
df1 <- structure(list(SampleID = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L
), Parameter = c("apple", "pear", "orange", "apple", "pear",
"orange", "apple", "pear", "orange"), Value = c(30L, 15L, 20L,
2L, 3L, 10L, 15L, 23L, 12L), Unit = c("g", "lb", "kg", "g", "lb",
"kg", "g", "lb", "kg")), class = "data.frame", row.names = c(NA,
-9L))
我有一个如下所示的数据框
Sample ID | Parameter | Value | Unit |
---|---|---|---|
1 | apple | 30 | g |
1 | pear | 15 | lb |
1 | organge | 20 | kg |
2 | apple | 2 | g |
2 | pear | 3 | lb |
2 | orange | 10 | kg |
3 | apple | 15 | g |
3 | pear | 23 | lb |
3 | orange | 12 | kg |
我想根据样本ID进行转置,把对应的值放到列中
Sample ID | apple_value_unit(g) | pear_value_unit(lb) | orange_value_unit(kg) |
---|---|---|---|
1 | 30 | 15 | 20 |
2 | 2 | 3 | 10 |
3 | 15 | 23 | 12 |
有什么方法可以转置和匹配值吗?我尝试了 cast(),但它无法将值映射到相应的参数。
在使用 pivot_wider
library(dplyr)
library(stringr)
library(tidyr)
df1 %>%
mutate(Parameter = sprintf('%s_value_unit(%s)', Parameter, Unit),
.keep = "unused") %>%
pivot_wider(names_from = Parameter, values_from = Value)
-输出
# A tibble: 3 × 4
SampleID `apple_value_unit(g)` `pear_value_unit(lb)` `orange_value_unit(kg)`
<int> <int> <int> <int>
1 1 30 15 20
2 2 2 3 10
3 3 15 23 12
数据
df1 <- structure(list(SampleID = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L
), Parameter = c("apple", "pear", "orange", "apple", "pear",
"orange", "apple", "pear", "orange"), Value = c(30L, 15L, 20L,
2L, 3L, 10L, 15L, 23L, 12L), Unit = c("g", "lb", "kg", "g", "lb",
"kg", "g", "lb", "kg")), class = "data.frame", row.names = c(NA,
-9L))