[英]R: subtracting the first row from itself and subsequent rows from next row in column & do this for multiple columns
[英]Subtracting multiple rows from the same row in R
我希望從 dataframe 中的同一行中減去多行。
例如:
Group A B C
A 3 1 2
B 4 0 3
C 4 1 1
D 2 1 2
這就是我想要的樣子:
Group A B C
B 1 -1 1
C 1 0 -1
D -1 0 0
換句話說:
B 行 - A 行
行 C - A 行
D行 - A行
謝謝!
這是一個dplyr
解決方案:
library(dplyr)
df %>%
mutate(across(A:C, ~ . - .[1])) %>%
filter(Group != "A")
這給了我們:
Group A B C
1: B 1 -1 1
2: C 1 0 -1
3: D -1 0 0
這是一種使用基礎 R 的方法:
data[-1] <- do.call(rbind,
apply(data[-1],1,function(x) x - data[1,-1])
)
data[-1,]
# Group A B C
#2 B 1 -1 1
#3 C 1 0 -1
#4 D -1 0 0
數據:
data <- structure(list(Group = c("A", "B", "C", "D"), A = c(3L, 4L, 4L,
2L), B = c(1L, 0L, 1L, 1L), C = c(2L, 3L, 1L, 2L)), class = "data.frame", row.names = c(NA,
-4L))
我們還可以復制第一行並從rep
中減去
cbind(data[-1, 1, drop = FALSE], data[-1, -1] - data[1, -1][col(data[-1, -1])])
-輸出
# Group A B C
#2 B 1 -1 1
#3 C 1 0 -1
#4 D -1 0 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.