-1

I try to get sum for each of the Flags 1-3 in my dataframe and keep same column names, so I get single row , but looks like I missing some df/Numeric conversion here, can you please advice , not sure whey I get dim(dfs) = NULL??

df <- data.frame(label=2017, F1=1:4, F2=2:5, F3=3:6)
df

dfs <-            c( max(df$label), sum(df$F1), sum(df$F2), sum(df$F3)) 
#dfs <- data.frame(c( max(df$label), sum(df$F1), sum(df$F2), sum(df$F3)) )
dfs
str(dfs)
dim(dfs)

colnames(dfs) <-c('Label', 'F1','F2','F3')
## Error in `colnames<-`(`*tmp*`, value = c("Label", "F1", "F2", "F3")) : 
##    attempt to set 'colnames' on an object with less than two dimensions 
Mike S
  • 296
  • 2
  • 14
  • 1
    Your `c()` creates a vector, not a data frame. If you use `as.data.frame(t(dfs))` you'll be able to set the column names. You might also be interested in `colSums()`, or maybe even the [How to sum variables by group? R-FAQ](https://stackoverflow.com/q/1660124/903061). – Gregor Thomas Jan 24 '18 at 20:37
  • Thanks much Gregor!!! Case solved. **I can't see a place to give a points to correct answers, is something changed on SOverflow ? Best. M – Mike S Jan 24 '18 at 21:24
  • aggregate(. ~ label, df, sum) ## this is perfect, Tx again G! – Mike S Jan 24 '18 at 21:31
  • @KevinArseneau I agree that this kind of question most likely has already been asked several times on SO but there must be better dupe targets, IMHO. The linked question does only aggregate one column while here the OP wants to aggregate multiple columns simultaneously. – Uwe Jan 25 '18 at 01:31

1 Answers1

0

Your c() creates a vector, not a data frame. If you convert your vector to a one-row data frame with as.data.frame(t(dfs)), you'll be able to set the column names.

You might also be interested in colSums(), or maybe even the How to sum variables by group? R-FAQ.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294