如何添加新列,并根据R中的其他列变量填写变量?

时间:2022-09-16 19:16:18

I'd appreciate any help I can get here.

我很感激我能得到的任何帮助。

I have a dataset that I've created, and I need to take the "Total Return Change" variable from the table "spReturns" based on the year of the return, and append it as a new column in "relativeTable". The catch is, that each return needs to be appended with the equal "year" in "relativeTable". So, for example, each observation in relativeTable with the "year" 1989, should have a new column of the return that matches the "Total Return Change". In this instance, every "year" of 1989 should have the return of 0.1661, from 1989 in the "spReturn" table. I'm totally clueless how to go about this, so I appreciate any help I can get.

我有一个我创建的数据集,我需要根据返回年份从表“spReturns”中获取“Total Return Change”变量,并将其作为“relativeTable”中的新列附加。问题是,每个返回都需要在“relativeTable”中附加相等的“year”。因此,例如,relativeTable中与“year”1989相关的每个观察都应该有一个与“总回报变化”匹配的新回归列。在这种情况下,1989年的每个“年”应该从1989年的“spReturn”表中返回0.1661。我完全不知道如何解决这个问题,所以我很感激我能得到的任何帮助。

require(Quandl)
require(lubridate)
require(zoo)
require(xts)

myData <- load(url("http://bit.ly/dasi_gss_data"))
myData <- myData

year <- gss$year
finSat <- gss$satfin

relativeTable <- data.frame(year, finSat)
relativeTable <- subset(relativeTable, year > "1988" & !is.na(finSat))


spReturns <- Quandl("SANDP/ANNRETS", trim_start="1970-01-11", 
                    trim_end="2012-12-31", authcode="nwy3a_Gmd7TSS9fVirxT", 
                    collapse="annual")

percentChange <- spReturns$"Total Return Change"

spReturns$"Year Ending" <- format((spReturns$"Year Ending"), "%Y")
spReturns$"Year Ending" <- as.numeric(spReturns$"Year Ending")
spReturns$"Year Ending" <- spReturns[,1] + 1 #the following year

1 个解决方案

#1


1  

combined <- merge(relativeTable, spReturns, by.x = "year", by.y = "Year Ending")

#1


1  

combined <- merge(relativeTable, spReturns, by.x = "year", by.y = "Year Ending")