Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中:如何从i+;1数据帧的第1行,并从i+中的每一行中减去;第二数据帧的第1列_R_Loops - Fatal编程技术网

在R中:如何从i+;1数据帧的第1行,并从i+中的每一行中减去;第二数据帧的第1列

在R中:如何从i+;1数据帧的第1行,并从i+中的每一行中减去;第二数据帧的第1列,r,loops,R,Loops,请注意,实际的数据集是1000列和100行,因此我正在寻找一种不需要手动命名列或行的方法 使用具有以下类似结构的数据集: subvalues <- c(1:10) df <- data.frame(x = rpois(40,2), y = rpois(40,2), z = rpois(40,2), q = rpois(40,2), t = rpois(40,2)) 我需要弄清楚“SVi+1”循环以及如何在循环中正确地执行循环 非常感谢任何帮助您提供的示例数据集将不起作用,因为您需

请注意,实际的数据集是1000列和100行,因此我正在寻找一种不需要手动命名列或行的方法

使用具有以下类似结构的数据集:

subvalues <- c(1:10)

df <- data.frame(x = rpois(40,2), y = rpois(40,2), z = rpois(40,2), q = rpois(40,2), t = rpois(40,2))
我需要弄清楚“SVi+1”循环以及如何在循环中正确地执行循环


非常感谢任何帮助

您提供的示例数据集将不起作用,因为您需要相同长度的
子值
df
列数

经过一些修改后,下面是一个示例。您不需要从子值中提取值,因为它只是一个减法。 请注意,我已将df保存在tmp中,以便在不丢失初始数据的情况下修改此data.frame。此外,如果整个数据帧是数字的,考虑使用矩阵,它可以节省你的时间。
subvalues <- c(1:5) # Note here the length 5 for the 5 columns of df.

df <- data.frame(x = rpois(40,2), y = rpois(40,2), z = rpois(40,2), q = rpois(40,2), t = rpois(40,2))
tmp <- df

for(i in seq_along(subvalues)){
  # print(subvalues[i]) 
  tmp[,i] <- tmp[,i] - subvalues[i]
}

子值也许您可以尝试
复制
来创建与
df
相同维度的矩阵,然后进行减法,即

dfout <- df - t(replicate(nrow(df),subvalues))
数据

set.seed(1)
subvalues <- c(1:5) # Note here the length 5 for the 5 columns of df.

df <- data.frame(x = rpois(40,2), y = rpois(40,2), z = rpois(40,2), q = rpois(40,2), t = rpois(40,2))

set.seed(1)
子值
length(子值)
为10,而
nrow(df)
为40。如何减去10后的行数?此外,最好使用
set.seed
给出一个可重复的示例,并显示预期输出,以使示例更清晰。
> dfout
    x  y  z  q  t
1   0  1 -1  2 -4
2   0  0  0 -2 -1
3   1  1 -2 -2 -3
4   3  0 -2 -3 -2
5   0  0  0 -1 -1
6   3  1 -2 -2 -3
7   3 -2  0 -2 -5
8   1  0 -3 -3 -4
9   1  1 -2 -3 -2
10 -1  1 -2 -2 -4
11  0  0 -2 -2 -3
12  0  2 -3 -4 -2
13  2  0 -1 -4 -2
14  0 -1  1 -2 -4
15  2 -2  0  0 -4
16  1 -2  0 -2 -1
17  2 -1 -1 -2 -3
18  5  0 -1 -2 -2
19  0  0  0  2 -3
20  2  0 -1 -2 -1
21  3  2 -1 -1 -4
22  0 -1 -2 -2 -4
23  1  0 -2 -3 -1
24 -1 -1  3 -3 -3
25  0  0 -1 -1 -1
26  0 -1 -2 -2 -4
27 -1  0 -3 -3 -2
28  0  1 -1 -1 -2
29  3 -2  1 -4 -1
30  0  2 -1  0 -3
31  1 -1  2 -2 -2
32  1  1  0 -2 -4
33  1 -1 -2 -3 -5
34  0 -1 -1 -2 -1
35  2  0 -2 -2 -4
36  1  2 -3 -3 -3
37  2  2  0 -2 -5
38 -1 -1 -3 -4 -2
39  2  1 -1 -3 -4
40  1  3 -1 -3 -2
set.seed(1)
subvalues <- c(1:5) # Note here the length 5 for the 5 columns of df.

df <- data.frame(x = rpois(40,2), y = rpois(40,2), z = rpois(40,2), q = rpois(40,2), t = rpois(40,2))