year <- rep(2014,3)
x1 <- c(1, 3, 5)
x2 <- c(2, 4, 6)
p1 <- data.frame(year, x1, x2)
year <- rep(2015,5)
x1 <- c(7, 8, 9, 10, 11)
x3 <- c(10, 11, 12, 13, 14)
x4 <- c(5, 4, 3, 2, 1)
p2 <- data.frame(year, x1, x3, x4)
p1
## year x1 x2
## 1 2014 1 2
## 2 2014 3 4
## 3 2014 5 6
p2
## year x1 x3 x4
## 1 2015 7 10 5
## 2 2015 8 11 4
## 3 2015 9 12 3
## 4 2015 10 13 2
## 5 2015 11 14 1
작업시간의 최소화를 위해 데이터프레임의 크기를 원 자료의 크기대로 할당한다. 0으로 생성되는 데이터를 몽땅싸그리 NA로 교체한다.
tp1 <- data.frame(year=numeric(nrow(p1)), v1 = numeric(nrow(p1)), v2 = numeric(nrow(p1)),
v3 = numeric(nrow(p1)), v4 = numeric(nrow(p1)))
for(i in 1:ncol(tp1)) tp1[,i] <- NA
tp1
## year v1 v2 v3 v4
## 1 NA NA NA NA NA
## 2 NA NA NA NA NA
## 3 NA NA NA NA NA
tp2 <- data.frame(year=numeric(nrow(p2)), v1 = numeric(nrow(p2)), v2 = numeric(nrow(p2)),
v3 = numeric(nrow(p2)), v4 = numeric(nrow(p2)))
for(i in 1:ncol(tp2)) tp2[,i] <- NA
tp2
## year v1 v2 v3 v4
## 1 NA NA NA NA NA
## 2 NA NA NA NA NA
## 3 NA NA NA NA NA
## 4 NA NA NA NA NA
## 5 NA NA NA NA NA
old <- as.character(c("year", "x1", "x2", "x3", "x4"))
new <- as.character(c("year", "v1", "v2", "v3", "v4"))
p1.names <- names(p1)
p1.names
## [1] "year" "x1" "x2"
np1 <- p1
for (i in p1.names)
{
names(np1)[which(names(np1)==i)] <- new[which(old==i)]
}
np1
## year v1 v2
## 1 2014 1 2
## 2 2014 3 4
## 3 2014 5 6
p1
## year x1 x2
## 1 2014 1 2
## 2 2014 3 4
## 3 2014 5 6
p2.names <- names(p2)
p2.names
## [1] "year" "x1" "x3" "x4"
np2 <- p2
for (i in p2.names)
{
names(np2)[which(names(np2)==i)] <- new[which(old==i)]
}
np2
## year v1 v3 v4
## 1 2015 7 10 5
## 2 2015 8 11 4
## 3 2015 9 12 3
## 4 2015 10 13 2
## 5 2015 11 14 1
p2
## year x1 x3 x4
## 1 2015 7 10 5
## 2 2015 8 11 4
## 3 2015 9 12 3
## 4 2015 10 13 2
## 5 2015 11 14 1
np1.names <- names(np1)
np1.names
## [1] "year" "v1" "v2"
for(i in np1.names)
{
tp1[names(tp1)==i] <- np1[names(np1)==i]
}
tp1
## year v1 v2 v3 v4
## 1 2014 1 2 NA NA
## 2 2014 3 4 NA NA
## 3 2014 5 6 NA NA
np2.names <- names(np2)
np2.names
## [1] "year" "v1" "v3" "v4"
for(i in np2.names)
{
tp2[names(tp2)==i] <- np2[names(np2)==i]
}
tp2
## year v1 v2 v3 v4
## 1 2015 7 NA 10 5
## 2 2015 8 NA 11 4
## 3 2015 9 NA 12 3
## 4 2015 10 NA 13 2
## 5 2015 11 NA 14 1
total <- rbind(tp1, tp2)
total
## year v1 v2 v3 v4
## 1 2014 1 2 NA NA
## 2 2014 3 4 NA NA
## 3 2014 5 6 NA NA
## 4 2015 7 NA 10 5
## 5 2015 8 NA 11 4
## 6 2015 9 NA 12 3
## 7 2015 10 NA 13 2
## 8 2015 11 NA 14 1