如果你想輸出的數據幀,請嘗試使用dplyr
# Recreating your sample data
df <- data.frame(SampleID = c(1, 2, 3),
a = c(0.1, 0.2, 0.5),
b = c(2, 3, 4),
d = c(1, 2, 3),
f = c(2, 3, 6),
ca = c(7, 4, 1),
k = c(1, 2, 3),
l = c(4, 5, 9),
cb = c(3, 5, 2))
處理數據
# load dplyr
library(dplyr)
# Sum across columns 'a' and 'ca' (sum(a, ca))
df2 <- df %>%
select(contains('a'), -SampleID) %>% # 'select' function to choose the columns you want
mutate(row_sum = rowSums(.)) # 'mutate' function to create a new column 'row_sum' with the sum of the selected columns. You can drop the selected columns by using 'transmute' instead.
df2 # have a look
a ca row_sum
1 0.1 7 7.1
2 0.2 4 4.2
3 0.5 1 1.5
謝謝!我得到了一個線索,略有修改它的工作! – Try
@OlgaAnufrieva感謝您的反饋。如果有效,請考慮通過點擊投票旁邊的勾號來接受解決方案。 – akrun
是否可以修改它,使其返回矩陣,data.frame和列的位置始終不是「+ 1」。所以,代碼可能會更普遍一些。 – Try