Picking specific values from a data.frame() based on index given by expand.grid()

Viewed 85

From my small data.frame (i) below, I wonder how to form the following data.frame of vectors?

# Desired output (2 rows x 6 columns):
data.frame(
mpre1=c(.21,1.61) , sdpre1=c(.28,1.5) , n1 = c(21,21), #group=1,control=F,outcome= 1 & 2 

mpre2=c(.12,1.13) , sdpre2=c(.25,.92) , n2 = c(16,16)) #group=2,control=T,outcome= 1 & 2 
#  mpre1 sdpre1 n1 mpre2 sdpre2 n2
#1  0.21   0.28 21  0.12   0.25 16
#2  1.61   1.50 21  1.13   0.92 16

The index values (for group & outcome) to extract the above vectors from i are given by:

rev(expand.grid(outcome = unique(i$outcome), 
                  group = unique(i$group)))

This is a toy example, a functional BASE R answer is highly appreciated.

i = read.csv("https://raw.githubusercontent.com/rnorouzian/m2/main/g.csv")

#  study.name group  n mpre sdpre mpos sdpos rev.sign post control outcome
#1     Diab_b     1 21 0.21  0.28 0.22  0.44     TRUE    1   FALSE       1
#2     Diab_b     1 21 0.21  0.28 0.08  0.11     TRUE    2   FALSE       1
#3     Diab_b     1 21 1.61  1.50 0.87  0.82     TRUE    1   FALSE       2
#4     Diab_b     1 21 1.61  1.50 1.97  1.04     TRUE    2   FALSE       2
#5     Diab_b     2 16 0.12  0.25 0.15  9.24     TRUE    1    TRUE       1
#6     Diab_b     2 16 0.12  0.25 0.08  0.11     TRUE    2    TRUE       1
#7     Diab_b     2 16 1.13  0.92 0.62  0.43     TRUE    1    TRUE       2
#8     Diab_b     2 16 1.13  0.92 0.84  0.55     TRUE    2    TRUE       2
1 Answers

In your dataset, there is also a variable called 'post' that have been used for grouping.
Nevertheless, I suppose we do not want to include that:

main_df <- read.csv("https://raw.githubusercontent.com/rnorouzian/m2/main/g.csv")

index <- rev(expand.grid(outcome = unique(main_df$outcome), group =unique(main_df$group)))

df_fin <- function(index){
    for (i in 1:nrow(index)) {
          #creating a variable of each index row(group-outcome combination)
          couple <- index[i,] 
          #subsetting one row of combination because they also are grouped by "post" variable
          subsetted_df <- subset(main_df, outcome == couple[,2] & group == couple[,1])[1,]
          name <- paste0("mpre",  couple[,1],couple[,2])
          assign(name, subsetted_df[,'mpre'])
          name1 <- paste0("sdpre", couple[,1],couple[,2])
          assign(name1, subsetted_df[,'sdpre'])
          name2 <- paste0("n", couple[,1],couple[,2])
          assign(name2, subsetted_df[,'n'])
    }

  final_df <- data.frame(
    mpre1 = c(mpre11, mpre12),
    sdpre1 = c(sdpre11, sdpre12),
    n1 = c(n11, n12),
    mpre2 = c(mpre21, mpre22), 
    sdpre2 = c(sdpre21, sdpre22),
    n2 = c(n21, n22)
  )
  return(final_df)
}

desired_df <- df_fin(index)
desired_df

##   mpre1 sdpre1 n1 mpre2 sdpre2 n2
## 1  0.21   0.28 21  0.12   0.25 16
## 2  1.61   1.50 21  1.13   0.92 16

Is it what you mean?

Related