R - 如何在数据框内转换值

时间:2017-03-27 15:42:42

标签: r

我有一个数据框(参见图片摘录),其中包含不同扇区的索引。每行是特定部门的索引所代表的月份。但我需要使用相对回报而不是指数 - 意味着 - > ln(月份指数t /月份指数t-1)。如何将我收到的表转移到包含相对回报的表中?例如第2行= ln(第2行/第1行)等。

欢迎任何帮助!

Data Frame

1 个答案:

答案 0 :(得分:0)

n <- nrow(df)
returns = apply(df, 2, function(x) log(x[-1]/x[-n]))

数据

df = structure(list(TOTXTER = c(2215.83, 2245.72, 2270.89, 2223.7, 
2424.06, 2474.17, 2588.63, 2524.26, 2538.74, 2729.11, 2544.33
), OILGSER = c(4674.38, 4676.73, 4637.56, 4573.83, 4983.08, 5244.84, 
5449.16, 5301.82, 5637.56, 5941.14, 5485.61), BMATRER = c(1660.95, 
1671.76, 1693.66, 1635.54, 1720.29, 1760.02, 1785.75, 1789.98, 
1789.09, 1887.73, 1716.61), CHMCLER = c(2103.37, 2105.47, 2108.5, 
2020.08, 2086.4, 2133.43, 2202.96, 2177.63, 2142.27, 2274.55, 
2108.15), BRESRER = c(1130.31, 1112.28, 1163.64, 1129.64, 1218.04, 
1262.35, 1271.25, 1296.26, 1280.15, 1331.12, 1110.19), INDUSER = c(1849.7, 
1847.57, 1858.19, 1820.16, 1963.64, 1986.84, 2026.37, 2053.58, 
2036.51, 2185.57, 1959.43), CNSTMER = c(1649.65, 1686.22, 1715.39, 
1670.04, 1774.8, 1808.93, 1786.93, 1799.99, 1844.09, 1928.18, 
1786.66), INDGSER = c(1823.64, 1820.19, 1830.12, 1787.6, 1925.63, 
1956.93, 1999.76, 2018.36, 2018.68, 2164.85, 1967.47), RITDVER = c(1073.32, 
1126.17, 1130.85, 1095.9, 1117.03, 1083.76, 1139.1, 1100.51, 
1120.35, 1138.33, 1125.28)), .Names = c("TOTXTER", "OILGSER", 
"BMATRER", "CHMCLER", "BRESRER", "INDUSER", "CNSTMER", "INDGSER", 
"RITDVER"), class = "data.frame", row.names = c("1", "2", "3", 
"4", "5", "6", "7", "8", "9", "10", "11"))