将列除以前一列[已解决]

huangapple go评论74阅读模式
英文:

Divide column by the previous column[SOLVED]

问题

我尝试将数据集中每一列除以同一行中前一列的值,但不希望硬编码数值。例如,如果我有以下表格:

日期         0         1       2
07/01/2022   5         4       3
08/01/2022   4         3       2
09/01/2022   2         2       1

我想要将标记为0到2的行除以前一个数(第一个数的情况下是NA)。

我尝试使用lag函数,但它适用于列而不是行。

英文:

I'm trying to divide each column in a dataset by the previous column in the dataset for each row, but not by hard coding the values. For example, if I had the table:

DATE         0         1       2
07/01/2022   5         4       3
08/01/2022   4         3       2
09/01/2022   2         2       1

I would want to divide rows labeled 0 through 2 by the preceding number(NA for the first one).

I tried lag, but that works in columns and not rows.

答案1

得分: 1

Base R 解决方案:

tdf <- t(df)
res <- tdf / c(NA, tdf[-length(tdf)])
res

输入数据:

df <- data.frame(x0 = 5, x1 = 4, x2 = 3)
英文:

Base R solution:

tdf &lt;- t(df)
res &lt;- tdf / c(NA, tdf[-length(tdf)])
res

Input Data:

df &lt;- data.frame(x0 = 5, x1 = 4, x2 = 3)

答案2

得分: 1

转置会在有多行时导致问题。另一种基于 R 的替代选项,不需要转置(使用稍微扩展的数据集来演示它在各行之间的向量化):

df[-1] / df[-ncol(df)]

或者如果你想要第一列为 NA

cbind(A = NA, df[-1] / df[-ncol(df)])

输出:

   A         B         C         D         E
1 NA 0.8000000 0.7500000 0.6666667 0.5000000
2 NA 0.8333333 0.8000000 0.7500000 0.6666667
3 NA 0.8571429 0.8333333 0.8000000 0.7500000

或者对特定列进行操作(根据注释)。在这里,仅对第 2 列到第 4 列进行操作:

cols <- 2:4
df[cols] / df[cols - 1]

#          B         C         D
#1 0.8000000 0.7500000 0.6666667
#2 0.8333333 0.8000000 0.7500000
#3 0.8571429 0.8333333 0.8000000

数据:

df <- data.frame(A = 5:7, B = 4:6, C = 3:5, D = 2:4, E = 1:3)
英文:

Transposing will cause problems if there are more than one row. An alternative base R option without transposing (using a slightly expanded dataset to demonstrate that its vectorized across rows):

df[-1] / df[-ncol(df)]

Or if you want the first column NA:

cbind(A = NA, df[-1] / df[-ncol(df)])

Output:

   A         B         C         D         E
1 NA 0.8000000 0.7500000 0.6666667 0.5000000
2 NA 0.8333333 0.8000000 0.7500000 0.6666667
3 NA 0.8571429 0.8333333 0.8000000 0.7500000

Or with specific columns (per comment). Here, columns 2 through 4 only:

cols &lt;- 2:4
df[cols] / df[cols - 1]

#          B         C         D
#1 0.8000000 0.7500000 0.6666667
#2 0.8333333 0.8000000 0.7500000
#3 0.8571429 0.8333333 0.8000000

Data

df &lt;- data.frame(A = 5:7, B = 4:6, C = 3:5, D = 2:4, E = 1:3)

huangapple
  • 本文由 发表于 2023年6月5日 07:23:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76402786.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定