考虑数据帧,DF:
df = tribble(
~Shares, ~Price1, ~Price2, ~Price3,
100, 9, 10, 11,
200, 5, 6, 7,
300, 3, 2, 1
)
第一种方法 - 可怕。硬编码。这可行,但你想要一个可重复的解决方案。
df$Value1 = df$Shares * df$Price1
df$Value2 = df$Shares * df$Price2
df$Value3 = df$Shares * df$Price3
第二条本办法 - 更好,但仍然不是很大。对于值集原单数据帧,按价格倍增,分配colnames,数据合并在一起
stockPrice = df[,2:4]
stockValue = df$Shares * stockPrice
colnames(stockValue) = c(paste("value", seq(1:3), sep = ""))
cbind(df, stockValue)
三(最好)的方法 - 定义一个函数!
calculateValues = function(df){
N = ncol(df)
L = N-1
stockPrice = df[,2:N]
stockValue = df$Shares * stockPrice
colnames(stockValue) = c(paste("value", seq(1:L), sep = ""))
cbind(df, stockValue)
}
calculateValues(df)
这应该输出一个新的数据帧,每次有份*值,命名和一切!唯一的问题是你的df的第一列每次都必须命名为“Shares”。
什么是您的预期输出 – Wen