如何在 r 中创建 for 循环并填充输出矩阵
How to create a for loop and fill an output matrix in r
这是一个由两部分组成的问题。
我有一个名为 Price 的 2x6 数据集。
我想创建一个 for 循环,它将 Price 中的特定行乘以 (1-h) 和 -1*(1-h)。这个结果应该填充一个只有 2x3 的新矩阵。
Price 的输入在第 1-3 行的第一列中有值,在第 4-6 行的第二列中有值。其他值只是零。
h <- .02
> Price
V1 V2
1 15.24 0.00
2 15.24 0.00
3 15.24 0.00
4 0.00 8.76
5 0.00 8.76
6 0.00 8.76
新矩阵应如下所示:
> effective.price
V1 V2
1 14.94 -8.58
2 15.24 -8.76
3 15.24 -8.76
我什至不知道从哪里开始,任何帮助将不胜感激。
谢谢
我认为这比您想象的要容易。如果你真的有这样固定的输入,那么
price <- read.table(text = "15.24 0.00
15.24 0.00
15.24 0.00
0.00 8.76
0.00 8.76
0.00 8.76")
newPrice <- as.data.frame(cbind(price$V1[1:3],price$V2[4:6]))
您在何处使用列绑定到列的设置部分。第一列取V1的值[1到3]等
产量
> newPrice
V1 V2
1 15.24 8.76
2 15.24 8.76
3 15.24 8.76
如果您需要更改 newPrice
的元素的值,您可以以矢量方式对其进行操作:
newPrice$V1 <- newPrice$V1 * (1 - h)
newPrice$V2 <- newPrice$V2 * (h - 1)
屈服
> newPrice
V1 V2
1 14.9352 -8.5848
2 14.9352 -8.5848
3 14.9352 -8.5848
我不确定 h
到底是什么,但我认为这符合您的要求。
df <- read.table(text = "V1 V2
1 15.24 0.00
2 15.24 0.00
3 15.24 0.00
4 0.00 8.76
5 0.00 8.76
6 0.00 8.76")
h <- 0.02
df$V1 <- df$V1 * (1 - h)
df$V2 <- - df$V2 * (1 - h)
effective.price <- data.frame(lapply(df, function(x) x[x != 0]))
这给出:
V1 V2
1 14.9352 -8.5848
2 14.9352 -8.5848
3 14.9352 -8.5848
你也可以通过整形来做到这一点:
library(dplyr)
library(tidyr)
df %>%
mutate(V1 = V1 * (1-h),
V2 = V2 * -(1-h),
ID = n() %>% `/`(2) %>% seq %>% rep(2)) %>%
gather(variable, value, -ID) %>%
filter(value != 0) %>%
spread(variable, value)
这是一个由两部分组成的问题。
我有一个名为 Price 的 2x6 数据集。
我想创建一个 for 循环,它将 Price 中的特定行乘以 (1-h) 和 -1*(1-h)。这个结果应该填充一个只有 2x3 的新矩阵。
Price 的输入在第 1-3 行的第一列中有值,在第 4-6 行的第二列中有值。其他值只是零。
h <- .02
> Price
V1 V2
1 15.24 0.00
2 15.24 0.00
3 15.24 0.00
4 0.00 8.76
5 0.00 8.76
6 0.00 8.76
新矩阵应如下所示:
> effective.price
V1 V2
1 14.94 -8.58
2 15.24 -8.76
3 15.24 -8.76
我什至不知道从哪里开始,任何帮助将不胜感激。
谢谢
我认为这比您想象的要容易。如果你真的有这样固定的输入,那么
price <- read.table(text = "15.24 0.00
15.24 0.00
15.24 0.00
0.00 8.76
0.00 8.76
0.00 8.76")
newPrice <- as.data.frame(cbind(price$V1[1:3],price$V2[4:6]))
您在何处使用列绑定到列的设置部分。第一列取V1的值[1到3]等
产量
> newPrice
V1 V2
1 15.24 8.76
2 15.24 8.76
3 15.24 8.76
如果您需要更改 newPrice
的元素的值,您可以以矢量方式对其进行操作:
newPrice$V1 <- newPrice$V1 * (1 - h)
newPrice$V2 <- newPrice$V2 * (h - 1)
屈服
> newPrice
V1 V2
1 14.9352 -8.5848
2 14.9352 -8.5848
3 14.9352 -8.5848
我不确定 h
到底是什么,但我认为这符合您的要求。
df <- read.table(text = "V1 V2
1 15.24 0.00
2 15.24 0.00
3 15.24 0.00
4 0.00 8.76
5 0.00 8.76
6 0.00 8.76")
h <- 0.02
df$V1 <- df$V1 * (1 - h)
df$V2 <- - df$V2 * (1 - h)
effective.price <- data.frame(lapply(df, function(x) x[x != 0]))
这给出:
V1 V2
1 14.9352 -8.5848
2 14.9352 -8.5848
3 14.9352 -8.5848
你也可以通过整形来做到这一点:
library(dplyr)
library(tidyr)
df %>%
mutate(V1 = V1 * (1-h),
V2 = V2 * -(1-h),
ID = n() %>% `/`(2) %>% seq %>% rep(2)) %>%
gather(variable, value, -ID) %>%
filter(value != 0) %>%
spread(variable, value)