簡體   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