Assuming I have a dataframe consisting of three columns
set.seed(24)
df1 <- data.frame(a=runif(10),b=runif(10),c=runif(10))
And want to have one with six columns of all interactions:
a*a, a*b, a*c, b*c, b*b, c*c
The solution I'm looking for should work for any number of columns, not just three
Here is another option with combn where do the combination of column names taking two at a time, multiply the columns after subsetting and cbind with square of the original dataset.
res <- cbind(df1^2, do.call(cbind,combn(colnames(df1), 2,
FUN= function(x) list(df1[x[1]]*df1[x[2]]))))
colnames(res)[-(seq_len(ncol(df1)))] <- combn(colnames(df1), 2,
FUN = paste, collapse=":")
res
# a b c a:b a:c b:c
#1 0.08559952 0.365890531 0.008823729 0.17697473 0.02748285 0.056820059
#2 0.05057603 0.137444401 0.304984209 0.08337501 0.12419698 0.204739766
#3 0.49592997 0.451167798 0.525871254 0.47301970 0.51068123 0.487089495
#4 0.26925425 0.452905189 0.019023202 0.34920860 0.07156869 0.092820832
#5 0.43906475 0.102675746 0.049713853 0.21232357 0.14774167 0.071445132
#6 0.84721676 0.817486693 0.472890881 0.83221898 0.63296215 0.621757189
#7 0.07825199 0.039249934 0.005850588 0.05542008 0.02139673 0.015153719
#8 0.58342170 0.001953909 0.359676293 0.03376319 0.45808619 0.026509902
#9 0.64261164 0.250923183 0.397086073 0.40155468 0.50514566 0.315655035
#10 0.06488487 0.019260683 0.002174826 0.03535148 0.01187911 0.006472142
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With