简体   繁体   中英

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.

I want to create a for loop that will multiply specific rows within Price by (1-h) and -1*(1-h). The results of this should fill a new matrix that is only 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. 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.

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$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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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