簡體   English   中英

矩陣中特定行的行數

[英]rowsums accross specific row in a matrix

final.marks
#          raj sanga rohan rahul
#physics    45    43    44    49
#chemistry  47    45    48    47
#total      92    88    92    96

這是我的矩陣。 現在,我想在各個主題行中分別查找每個主題的總數,並將它們作為新列添加到上述矩陣的第5列中。 但是我的代碼即class.marks.chemistry<- rowSums(final.marks[2,])一直產生錯誤提示

錯誤顯示rowSums(final.marks [2,]):“ x”必須是至少二維數組

你能幫我解決嗎。 我對R或任何形式的腳本或編程背景都很陌生。

你是這個意思嗎

# Sample data
df <- read.table(text =
    "          raj sanga rohan rahul
physics    45    43    44    49
chemistry  47    45    48    47
total      92    88    92    96", header  = T)

# Add column total with row sum
df$total <- rowSums(df);
df;
#          raj sanga rohan rahul total
#physics    45    43    44    49   181
#chemistry  47    45    48    47   187
#total      92    88    92    96   368

如果dfmatrix而不是data.frame則以上內容也適用。


如果查看?rowSums ,可以看到x參數必須為

包含數字,復數,整數或邏輯值或數字數據框的二維或二維數組。

因此,在您的情況下,我們必須將整個data.frame (或matrix )作為參數傳遞,而不是將特定列作為參數傳遞。

另一種選擇是在matrix上使用addmargins

addmargins(as.matrix(df), 2)
#         raj sanga rohan rahul Sum
#physics    45    43    44    49 181
#chemistry  47    45    48    47 187
#total      92    88    92    96 368

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM