[英]How to create a for loop and fill an output matrix in r
This is a two part question. 这是一个两部分的问题。
I have a data set that is 2x6 named Price. 我有一个名为Price的2x6数据集。
I want to create a for loop that will multiply specific rows within Price by (1-h) and -1*(1-h). 我想创建一个for循环,将Price中的特定行乘以(1-h)和-1 *(1-h)。 The results of this should fill a new matrix that is only 2x3.
这样的结果应该填充一个只有2x3的新矩阵。
The input of Price has values in the first column of rows 1-3, and values in the second column of rows 4-6. 价格输入在第1-3行的第一列中有值,在第4-6行的第二列中有值。 The other values are just zeros.
其他值只是零。
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
The new matrix should look as the following: 新矩阵应如下所示:
> effective.price
V1 V2
1 14.94 -8.58
2 15.24 -8.76
3 15.24 -8.76
I don't even know where to begin, any help would be greatly appreciated. 我什至不知道从哪里开始,任何帮助将不胜感激。
Thanks 谢谢
I think that it's easier than you think. 我认为这比您想象的要容易。 If you really have a fixed input like that, then
如果您确实有这样的固定输入,那么
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]))
where you are using column binds over set sections of your columns. 您在其中使用列绑定的位置在列的设置部分上。 The first column takes the values of V1[1 to 3], etc.
第一列采用V1 [1至3]等值。
Yields 产量
> newPrice
V1 V2
1 15.24 8.76
2 15.24 8.76
3 15.24 8.76
If you need to change the value of the elements of newPrice
you can operate on that in a vector fashion: 如果您需要更改
newPrice
元素的值,则可以矢量方式对其进行操作:
newPrice$V1 <- newPrice$V1 * (1 - h)
newPrice$V2 <- newPrice$V2 * (h - 1)
yielding 屈服
> newPrice
V1 V2
1 14.9352 -8.5848
2 14.9352 -8.5848
3 14.9352 -8.5848
I'm not sure exactly what the h
is but I think this does what you want. 我不确定
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]))
This gives: 这给出:
V1 V2
1 14.9352 -8.5848
2 14.9352 -8.5848
3 14.9352 -8.5848
You can also do this with reshaping: 您也可以通过重塑来做到这一点:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.