以下是示例数据:
A <- read.table(text = "id Person X2012 X2011 X2010 X2009 X2013 X2008 X2007
1 1 Name 1.3 NA 1.5 0.23 0.25 NA NA
2 2 Name NA NA 0.1 NA NA NA NA
3 3 Name NA NA NA NA NA 0.95 0.30
4 4 Name -1.69 1 0.2 NA NA NA NA", header = TRUE)
这是我想要的:
year id Person X2012 X2011 X2010 X2009 X2013 X2008 X2007
1 X2009 1 Name 1.30 NA 1.5 0.23 0.25 NA NA
2 X2010 1
3 X2012 1
4 X2013 1
5 X2010 2 Name NA NA 0.1 NA NA NA NA
6 X2007 3 Name NA NA NA NA NA 0.95 0.3
7 X2008 3
7 X2010 4 Name -1.69 1 0.2 NA NA NA NA
8 X2011 4
9 X2012 4
所以基本上,如果是数字(如果不是NA)则获取列名并创建新行:类似t(sort(colnames(x))
。我追求的是年本身,休息并不重要。
答案 0 :(得分:2)
reshape2
救援:
library(reshape2)
A_melt <- melt(A, id.vars=c("id", "Person"))
A_val <- A_melt[!is.na(A_melt$value), ]
A_val$variable <- as.character(A_val$variable)
A_val[with(A_val, order(id, variable)), ]
id Person variable value
13 1 Name X2009 0.23
9 1 Name X2010 1.50
1 1 Name X2012 1.30
17 1 Name X2013 0.25
10 2 Name X2010 0.10
27 3 Name X2007 0.30
23 3 Name X2008 0.95
12 4 Name X2010 0.20
8 4 Name X2011 1.00
4 4 Name X2012 -1.69