2017-10-11 56 views
2

我想在工作表中寫入我的data.frame時添加總行(如在Excel表中)。 這裏是(使用openxlsx)我的本的代碼:R - 在Excel輸出中添加總行

writeDataTable(wb=WB, sheet="Data", x=X, withFilter=F, bandedRows=F, firstColumn=T) 

X包含8個字符變量和1個數字可變一個data.frame。因此總行應該只包含數字行的總數(如果以某種方式我可以添加Excel總行數功能,那麼最好的方法是最好的,就像我在將表寫入工作簿對象時使用firstColumn一樣,而不是手動添加總行) 。

我在StackOverflow和官方的openxslx文檔中搜索了一個解決方案,但無濟於事。請使用openxlsx建議解決方案。

編輯:

添加數據樣本:

A B C D E F G H I 
a b s r t i s 5 j 
f d t y d r s 9 s 
w s y s u c k 8 f 

總計行後:

A B C D E F G H I 
    a b s r t i s 5 j 
    f d t y d r s 9 s 
    w s y s u c k 8 f 
    na na na na na na na 22 na 
+0

請提出改進​​的問題沒有徹底downvoting首先使用lapply

totals <- lapply(df, function(col) { ifelse(!any(!is.numeric(col)), sum(col), NA) }) 

,並把它添加到df。 – Arani

回答

1

假設您的數據存儲在一個名爲data.frame DF:

df <- read.table(text = 
    "A B C D E F G H I 
    a b s r t i s 5 j 
    f d t y d r s 9 s 
    w s y s u c k 8 f", 
       header = TRUE, 
       stringsAsFactors = FALSE) 

您可以創建一個行使用rbind()

df <- rbind(df, totals) 

head(df) 
    A B C D E F G H I 
1 a b s r t i s 5 j 
2 f d t y d r s 9 s 
3 w s y s u c k 8 f 
4 <NA> <NA> <NA> <NA> <NA> <NA> <NA> 22 <NA>