Emma
Emma

Reputation: 1

Make simple table from data frame using formula

I've got a large dataframe with 72 rows and 72 columns. All are numbers. I just want to make a table with the sum of the the first row multiplied by the sum of the first column and so on and so forth. So for example, if this is my df

x0 <- c(0,0,11,0)
x0.1 <- c(0,251,0,0)
x0.2 <- c(0,495,0,0)
x0.4 <- c(0,0,0,6)
df <- data.frame(x0,x0.1,x0.2,x0.4)

I want my table to look something like this

1 0
2 124911
3 5445
4 36

Upvotes: 0

Views: 91

Answers (3)

TarJae
TarJae

Reputation: 78937

Here is a tidyverse approach:

library(dplyr)
library(tidyr)

df %>% 
  unite(x, c(x0, x0.1, x0.2, x0.4), sep = "") %>% 
  mutate(x = sub("^0+(?!$)", "", x, perl=TRUE))
        x
1       0
2 2514950
3   11000
4       6

Upvotes: 0

Henry Cyranka
Henry Cyranka

Reputation: 3060

Solution using sapply:

sapply(1:nrow(df), function(i){sum(df[i,]*sum(df[,i]))})

Upvotes: 0

Sweepy Dodo
Sweepy Dodo

Reputation: 1873

Would you be looking for:

rowSums(df)*colSums(df)

Upvotes: 1

Related Questions