如何创建for循环并在r中填充输出矩阵
这是一个由两部分组成的问题 我有一个数据集是2x6命名价格 我想创建一个for循环,将Price中的特定行乘以(1-h)和-1*(1-h)。这一结果将填充一个仅为2x3的新矩阵 Price的输入值在第1-3行的第一列中,值在第4-6行的第二列中。其他值只是零如何创建for循环并在r中填充输出矩阵,r,for-loop,output,R,For Loop,Output,这是一个由两部分组成的问题 我有一个数据集是2x6命名价格 我想创建一个for循环,将Price中的特定行乘以(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 我甚至不
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
我甚至不知道从哪里开始,任何帮助都将不胜感激
谢谢我想这比你想象的要容易。如果你真的有这样一个固定的输入,那么
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]))
如果您需要更改newPrice
元素的值,您可以以向量方式对其进行操作:
newPrice$V1 <- newPrice$V1 * (1 - h)
newPrice$V2 <- newPrice$V2 * (h - 1)
我不确定
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]))
您也可以通过重塑来实现这一点:
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)
感谢您的反馈!我使用这种方法,然后指定要更改的确切点。你能简单解释一下Lappy函数中发生了什么吗?感谢您的帮助。
lappy
步骤从每个变量中去掉零,并将其放回data.frame
中。这就像做a一样
> newPrice
V1 V2
1 14.9352 -8.5848
2 14.9352 -8.5848
3 14.9352 -8.5848
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)