E.Mestri
E.Mestri

Reputation: 3

multiply all columns in data frame in R

I need to multiply all columns in a data frame with each other. As an example, I need to achieve the following:

mydata$C1_2<-mydata$sic1*mydata$sic2

but for all my columns with values going from 1 to 733 (sic1, sic2, sic3,..., sic733).

I've tried the following but it doesn't work:

for(i in 1:733){
for(j in 1:733){
mydata$C[i]_[j]<-mydata$sic[i]*mydata$sic[j]
}
}

Could you help me? Thanks for your help.

Upvotes: 0

Views: 2271

Answers (1)

Georgery
Georgery

Reputation: 8127

Despite the question if you really want what you think you want, I feel like this could help:

df <- data.frame(
    a = 1:4
    , b = 1:4
    , c = 4:1
)

multiplyColumns <- function(name1, name2, df){
    df[, name1] * df[, name2]
}

combinations <- expand.grid(names(df), names(df), stringsAsFactors = FALSE)
names4result <- paste(combinations[,1], combinations[,2], sep = "_")

result <- as.data.frame(mapply(multiplyColumns, combinations[,1],     combinations[,2], MoreArgs = list(df = df)))
names(result) <- names4result
result

Upvotes: 1

Related Questions