提问人:Jin.w.Kim 提问时间:11/12/2023 更新时间:11/12/2023 访问量:69
在 R 中,当将数据从行转置到列时,为什么 spread() 代码不起作用?
In R, when transpose data from row to column, why spread() code doesn't work?
问:
我在下面有一个数据
dataA= data.frame(
Location = rep(c("East", "West", "North"), each = 12 * 2),
Season = rep(rep(c(2021, 2022), each = 6), 3),
Genotype = rep(rep(c("CV1", "CV2"), each = 6), 3),
Iron_ton_ha = rep(c(21.7127, 16.9369, 30.7798, 14.0833, 13.2023, 11.1327, 15.0424,
9.6616, 5.8569, 6.1881, 8.0127, 6.0291), each = 6),
Stage = rep(c("Vegetative", "Reproductive", "Maturity"), each = 12),
Fe = rep(c(0.44, 0.36, 0.31, 0.28, 0.79, 0.38, 0.59, 0.35, 0.41, 0.4, 0.29, 0.27,
0.37, 0.3, 0.31, 0.28, 0.16, 0.24, 0.57, 0.27, 0.23, 0.26, 0.26, 0.27,
0.13, 0.15, 0.04, 0.06, 0.03, 0.23, 0.52, 0.06, 0.08, 0.11, 0.1, 0.04),
each = 2)
)
我想将 Stage 列中的每个变量移动到每列,我使用了以下代码。但是缺少一些数据,显示NA。你能告诉我为什么它不起作用吗?
谢谢
library(dplyr)
library(tidyverse)
dataB= dataA %>%
group_by(Location, Season, Genotype, Iron_ton_ha, Stage) %>%
summarise(Fe = mean(Fe, na.rm = TRUE)) %>%
spread(key = Stage, value = Fe)
dataB
# A tibble: 12 × 7
# Groups: Location, Season, Genotype, Iron_ton_ha [12]
Location Season Genotype Iron_ton_ha Maturity Reproductive Vegetative
<chr> <dbl> <chr> <dbl> <dbl> <dbl> <dbl>
1 East 2021 CV1 21.7 NA NA 0.37
2 East 2021 CV1 30.8 NA 0.45 NA
3 East 2022 CV2 14.1 NA 0.32 NA
4 East 2022 CV2 16.9 NA NA 0.483
5 North 2021 CV1 5.86 NA 0.107 NA
6 North 2021 CV1 8.01 0.22 NA NA
7 North 2022 CV2 6.03 0.0833 NA NA
8 North 2022 CV2 6.19 NA 0.107 NA
9 West 2021 CV1 13.2 0.327 NA NA
10 West 2021 CV1 15.0 NA NA 0.357
11 West 2022 CV2 9.66 NA NA 0.263
12 West 2022 CV2 11.1 0.227 NA NA
答: 暂无答案
评论