Sebastian Zeki
Sebastian Zeki

Reputation: 6874

Loop to count number of rows in each column and save output

I think this is pretty simple. I have a dataframe called df. It has 51 columns. The rows in each column contains random integers. All I want to do as a loop is add all the integers in all the rows of each column and then store the output for each of the columns in a seperate list or dataframe. The df looks like this

Col1 col2 col3 col4
  34    12    33    67
  22      1    56    66

Etc

The output I want is:

 Col1 col2 col3 col4
   56    13   89  133

I do want to do this as a loop as I want to apply what I've learnt here to a more complex script with similar output and I need to do it quick- can't quite master functions as yet...

Upvotes: 0

Views: 1268

Answers (2)

Drenmi
Drenmi

Reputation: 8777

You can use the built in function colSums for this:

> df <- data.frame(col1 = c(1,2,3), col2 = c(2,3,4))

> colSums(df)

col1 col2
   6    9

Another option using a loop:

# Create the result data frame
> res <- data.frame(df[1,], row.names = c('count'))

# Populate the results
> for(n in 1:ncol(df)) { res[colnames(df)[n]] <- sum(df[n]) }

col1 col2
   6    9

Upvotes: 2

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

If you really want to use a loop over a vectorized solution, use apply to loop over columns (second argument equal to 2, 1 is to loop over rows), by mentioning the function you want (here sum):

df = data.frame(col1=1:3,col2=2:4,col3=3:5)

apply(df, 2, sum)

#col1 col2 col3 
#   6    9   12 

Upvotes: 1

Related Questions