R将数据帧从长转换为宽

时间:2014-10-06 14:04:31

标签: r formatting

我试图将数据框从长格式转换为宽格式,但我遇到了同样的问题 - 我得到了NA。我认为我使用的聚合函数可能有问题:

library(reshape2)
library(plyr)

ID_NUMERIC <- c(5525,5525,5525,5525,5525,8523,8523,8523,8523,8523,4569,4569,4569,4569,4569)
SAMPLE_NAME <-c("HX44","HX44","HX44","HX44","HX44","RT5","RT5","RT5","RT5","RT5","OP1","OP1","OP1","OP1","OP1")
DATE <- c(as.Date("1/1/2014","1/1/2014","1/1/2014","1/1/2014","1/1/2014","1/15/2014","1/15/2014","1/15/2014","1/15/2014","1/15/2014","1/3/2014","1/3/2014","1/3/2014","1/3/2014","1/3/2014"))
ANALYSIS<- c("P8","P8","P8","P8","P8","P8","P8","P8","P8","P8","P8","P8","P8","P8","P8")
COMPONENT_NAME <- c("Density","Gravity","C6","C7","C8","Density","Gravity","C6","C7","C8","Density","Gravity","C6","C7","C8")
RESULT <- c(0.8593,33.13,2.1,2.3,2.2,0.8593,33.13,2.1,2.3,2.2,0.8593,33.13,2.1,2.3,2.2)
NAME <- c("HX","HX","HX","HX","HX","RT","RT","RT","RT","RT","OP","OP","OP","OP","OP")

first <- data.frame(ID_NUMERIC,SAMPLE_NAME,DATE,COMPONENT_NAME,ANALYSIS,RESULT,NAME)

second <- ddply(first, .(COMPONENT_NAME), function(x){x$id=1:nrow(x);x})
last <- dcast(second, NAME+SAMPLE_NAME+DATE+ID_NUMERIC+ANALYSIS+id~COMPONENT_NAME, value.var="RESULT")

1 个答案:

答案 0 :(得分:0)

您可以将数据放入矩阵并从那里开始使用吗?

ID_NUMERIC <- c(5525,5525,5525,5525,5525,8523,8523,8523,8523,8523,4569,4569,4569,4569,4569)
SAMPLE_NAME <-c("HX44","HX44","HX44","HX44","HX44","RT5","RT5","RT5","RT5","RT5","OP1","OP1","OP1","OP1","OP1")
COMPONENT_NAME<-c("Density","Gravity","C6","C7","C8","Density","Gravity","C6","C7","C8","Density","Gravity","C6","C7","C8")
NAME<-c("HX","HX","HX","HX","HX","RT","RT","RT","RT","RT","OP","OP","OP","OP","OP")
ANALYSIS<-c("P8","P8","P8","P8","P8","P8","P8","P8","P8","P8","P8","P8","P8","P8","P8")
DATE <- c("1/1/2014","1/1/2014","1/1/2014","1/1/2014","1/1/2014","1/15/2014","1/15/2014","1/15/2014","1/15/2014","1/15/2014","1/3/2014","1/3/2014","1/3/2014","1/3/2014","1/3/2014")
RESULT <- c(0.8593,33.13,2.1,2.3,2.2,0.8593,33.13,2.1,2.3,2.2,0.8593,33.13,2.1,2.3,2.2)
data<-matrix(c(ID_NUMERIC,SAMPLE_NAME,DATE,ANALYSIS,COMPONENT_NAME,RESULT,NAME),nrow=7,byrow=TRUE)
rownames(data)<-c("ID_NUMERIC","SAMPLE_NAME","DATE","ANALYSIS","COMPONANT_NAME","RESULT","NAME")
View(data)
data.frame(data)