重新排列纵向数据

标签 r data-manipulation

我有一个大致如下结构的数据集:

case Year      2001 2002 2003 2004
1    2003      0    0    0    3
2    2002      0    5    3    2
3    2001      3    3    2    2

我正在尝试对其进行重组,以便每一列代表从“年”变量开始计算的第一年、第二年(等等),即:

case Year      yr1  yr2  yr3 yr4
1    2003      0    3    0    0 
2    2002      5    3    2    0
3    2001      3    3    2    2

此代码下载数据集并尝试@akrun 建议的解决方案,但失败了。

library("devtools")
df1 <- source_gist("b4c44aa67bfbcd6b72b9")

df1[-(1:2)] <- do.call(rbind,lapply(seq_len(nrow(df1)), function(i) {x <- df1[i, ]; x1 <- unlist(x[-(1:2)]); indx <- which(!is.na(x1))[1]; i <- as.numeric(names(indx))-x[,2]+1; x2 <- x1[!is.na(x1)]; x3 <- rep(NA, length(x1)); x3[i:(i+length(x2)-1)]<- x2; x3}))

这会产生:

Error in i:(i + length(x2) - 1) : NA/NaN argument
In addition: Warning message:
In FUN(1:234[[1L]], ...) : NAs introduced by coercion

如何转换数据,使每一列代表第一年、第二年(等等),从每一行的“年”变量中的值开始计算?

最佳答案

这里有一个可能性:

library(dplyr)
library(reshape2)

df %>%
  melt(id.vars = c("case", "Year")) %>%
  mutate(variable = as.numeric(as.character(variable)),
         yr = variable - Year + 1) %>%
  filter(variable >= Year) %>%
  dcast(case + Year ~ yr, fill = 0)

#   case Year 1 2 3 4
# 1    1 2003 0 3 0 0
# 2    2 2002 5 3 2 0
# 3    3 2001 3 3 2 2

数据:

df <- structure(list(case = 1:3, Year = c(2003L, 2002L, 2001L), `2001` = c(0L, 
0L, 3L), `2002` = c(0L, 5L, 3L), `2003` = c(0L, 3L, 2L), `2004` = c(3L, 
2L, 2L)), .Names = c("case", "Year", "2001", "2002", "2003", 
"2004"), class = "data.frame", row.names = c(NA, -3L))

关于重新排列纵向数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28769805/

相关文章:

R 将列出的矩阵中的行附加到矩阵/数据帧,同时跳过缺失值

r - 通过变量的唯一组合添加变量以对数据进行分组

r - 在三维空间中为矢量设置动画

使用 fct_relevel 按组对因子重新排序仅更改第一组中的因子顺序

r - 填充R渐变曲线

r - 如何根据r中的日期/天拆分和制作新的csv文件?

r - 理解 glm$residuals 和 resid(glm)

r - mgcv:如何设置样条线的结的数量和/或位置

python-3.x - 在三列 Pandas 上应用 RMS 公式

regex - 使用 UNIX/Linux 操作(排除行).csv 文件的特定列