我有一张表格,其中包含来自各种样本(“ sample1”等)的数据,使用这些数据进行了几种类型的测量(A至C)。每次测量均给出3个值:浓度,最大值和最小值。
my.sample <- c("sample1", "sample1", "sample2", "sample2", "sample3")
type <- c("A", "B", "A", "C", "C")
concentration <- c(12, 5, 7, 10, 14)
max <- c(13, 6, 7, 11, 15)
min <- c(11, 4, 6, 9, 13)
mydata <- data.frame(my.sample, type, concentration, max, min)
> mydata
my.sample type concentration max min
1 sample1 A 12 13 11
2 sample1 B 5 6 4
3 sample2 A 7 7 6
4 sample2 C 10 11 9
5 sample3 C 14 15 13
我想将此数据转换为一个新表,其中每个样本只有一行。这意味着针对每种测量类型创建3列(浓度,最大值,最小值),并在该列中指示测量类型。缺少的值应定义为NA
。这是我想要获得的结果的一个示例:
A_concentration <- c(12, 7, NA)
A_max <- c(13, 7, NA)
A_min <- c(11, 6, NA)
B_concentration <- c(5, NA, NA)
B_max <- c(6, NA, NA)
B_min <- c(4, NA, NA)
C_concentration <- c(NA, 10, 14)
C_max <- c(NA, 11, 15)
C_min <- c(NA, 9, 13)
mydata.new <- data.frame(my.sample.new, A_concentration, A_max, A_min, B_concentration, B_max, B_min, C_concentration, C_max, C_min)
> mydata.new
my.sample.new A_concentration A_max A_min B_concentration B_max B_min
1 sample1 12 13 11 5 6 4
2 sample2 7 7 6 NA NA NA
3 sample3 NA NA NA NA NA NA
C_concentration C_max C_min
1 NA NA NA
2 10 11 9
3 14 15 13
有没有一种方法可以根据条件来扩大数据并 type
在列名中包含一个值(在这里:from )?我的真实数据集中有更多类型,因此理想情况下应该具有可概括性。
这有效:
library(dplyr)
mydata %>%
pivot_wider(id_cols = my.sample, names_from = type, values_from = c(concentration, max, min), names_glue = "{type}_{.value}") %>%
select(my.sample, starts_with("A"), starts_with("B"), starts_with("C"))
这给了我们:
# A tibble: 3 x 10
my.sample A_concentration B_concentration C_concentration A_max B_max C_max A_min B_min C_min
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 sample1 12 5 NA 13 6 NA 11 4 NA
2 sample2 7 NA 10 7 NA 11 6 NA 9
3 sample3 NA NA 14 NA NA 15 NA NA 13
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句