2015-10-28 99 views
0

這是一個兩部分問題。如何創建for循環並在r中填充輸出矩陣

我有一個數據集是2x6名爲Price。

我想創建一個for循環,將價格乘以(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 

我甚至不知道從哪裏開始,任何幫助將不勝感激。

謝謝

回答

0

我不知道確切的什麼是但我認爲這是你想要的。

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 
+0

我用這種方法,然後指定確切的點來改變。你能簡單解釋一下lapply函數中發生了什麼嗎?謝謝你的幫助。 – Bumperball

+0

'lapply'步驟從每個變量中去掉零並將其放回到'data.frame'中。這就像做'a < - df $ V1 [df $ V1!= 0]','b < - df $ V2 [df $ V2!= 0]'然後'effective.price < - data.frame( a,b)'。 – christoph

0

我認爲這比您想象的要容易。如果你確實有這樣一個固定的輸入,那麼

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 
+0

感謝您的反饋! – Bumperball

0

您還可以重塑做到這一點:

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)