如何在R中组合两个数据帧?

时间:2017-08-18 05:26:58

标签: r

我正在尝试加载csv文件并显示日期,工资和百分比变化。不幸的是,其中一个数据集有42行3列,另一个有41行2列。我的数据文件是here

所以我尝试了这两个但没有机会

rbind.fill(data,datadiff)
bind_rows(data,datadiff)

一旦我尝试组合它们,我得到如下结果,第二个数据帧从第一个数据帧结束的地方开始 http://imgur.com/a/pr8eZ

那么有没有办法将它们展示在一起更整洁?这是我的代码:

location <- read.csv("C:/Users/melik/Desktop/sydney-melbourne-rent-master/Average_Wages.csv", stringsAsFactors=T,header=TRUE)
x1 <- as.Date(location[,1],format = "%d/%m/%Y")
data <- data.frame(x1, x2 <- location[,2],x3 <- location[,3])
colnames(data) <- c("Date","Sydney Wages","Melbourne Wages")
x2diff <- diff(data[,2])/data[-nrow(data),2] * 100
x3diff <- diff(data[,3])/data[-nrow(data),3] * 100
colnames(datadiff) <- c("Sydney Difference","Melbourne Difference")
datadiff <- data.frame(x2diff,x3diff)
rbind.fill(data,datadiff)

2 个答案:

答案 0 :(得分:1)

正如OP的评论中所提到的,在datadiff中添加一行NAs然后执行cbind是最有效的方法。

dates = sample(seq(as.Date('2013/01/01'), as.Date('2016/01/01'), by="day"), 40)
sydneyWages = runif(n = 40, min = 1300, max = 1600)
melbourneWages = runif(n = 40, min = 1300, max = 1600)

startData = data.frame(dates, sydneyWages, melbourneWages)
x2diff <- diff(startData[,2])/startData[-nrow(startData),2] * 100
x3diff <- diff(startData[,3])/startData[-nrow(startData),3] * 100

datadiff = data.frame(x2diff, x3diff)
datadiff = rbind(datadiff, NA)

finalData = cbind(startData, datadiff)

#alternatively you can add the date to datadiff and use a merge
#this is only possible if every date is unique
datadiff = cbind(dates, datadiff)
finalData = merge(x = startData, y = datadiff, by = "dates", sort = F)

答案 1 :(得分:0)

非常感谢大家,现在效果很好。这是我的代码的最新版本:)

location <- read.csv("C:/Users/melik/Desktop/sydney-melbourne-rent-master/Average_Wages.csv", stringsAsFactors=T,header=TRUE)
x1 <- as.Date(location[,1],format = "%d/%m/%Y")
data <- data.frame(x1, x2 <- location[,2],x3 <- location[,3])
colnames(data) <- c("Date","Sydney Wages","Melbourne Wages")
x2diff <- diff(data[,2])/data[-nrow(data),2] * 100
x3diff <- diff(data[,3])/data[-nrow(data),3] * 100
datadiff <- data.frame(x2diff,x3diff)
colnames(datadiff) <- c("Sydney Difference","Melbourne Difference")
#diff(data[,2])/data[-nrow(data),2] * 100
datadiff = rbind(datadiff, NA)
finalData = cbind(data, datadiff)
finalData

My code