Home > Net >  Make simple table from data frame using formula
Make simple table from data frame using formula

Time:01-28

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

CodePudding user response:

Would you be looking for:

rowSums(df)*colSums(df)

CodePudding user response:

Solution using sapply:

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

CodePudding user response:

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
  •  Tags:  
  • Related