繁体   English   中英

如何在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的新矩阵。

价格输入在第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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM