r - 在 R 中带来长到宽的数据而不会丢失值
问题描述
您好我正在尝试使用该spread()
功能将数据从长格式转换为宽格式。实际上它有效,但是它给了我一半的数据框,每个转换后的列都有 NA。
我的数据框的一个最小示例:
Trial <- c(1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6)
Period <- c(4, 5, 6, 4, 5, 6)
variable <- c("SpotRate", "SpotSpread")
value <- c(0.5, 0.4, 0.2, 0.3, 0.6)
df <- cbind(Trial,Period,variable,value)
Wide_data <- spread(df, variable, value, convert=TRUE)
我想将变量转换为两列“SpotRate”和“SpotSpread”以及相应的值。这可行,但是由于其他变量的每个值都存在两次(试用、期间等),所以 SpotRate 和 SpotSpread 列的一半都填充了 NA。一旦我将其转换为宽数据,我如何告诉 R 它应该将所有重复值合并为一个?
谢谢!:)
解决方案
也许你正在寻找这个:
library(tidyverse)
#Data
Trial <- c(1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6)
Period <- c(4, 5, 6, 4, 5, 6)
variable <- c(rep("SpotRate",6),rep("SpotSpread",6))
value <- c(0.5, 0.4, 0.2, 0.3, 0.6)
df <- as.data.frame(cbind(Trial,Period,variable,value),stringsAsFactors = F)
#Code
df %>%
arrange(Trial) %>%
group_by(Trial) %>%
pivot_wider(names_from = variable,values_from=value) %>% ungroup()
输出:
# A tibble: 6 x 4
Trial Period SpotRate SpotSpread
<chr> <chr> <chr> <chr>
1 1 4 0.5 0.4
2 2 5 0.4 0.2
3 3 6 0.2 0.3
4 4 4 0.3 0.6
5 5 5 0.6 0.5
6 6 6 0.5 0.4