AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 77773544
Accepted
firmo23
firmo23
Asked: 2024-01-07 22:54:29 +0800 CST2024-01-07 22:54:29 +0800 CST 2024-01-07 22:54:29 +0800 CST

Aplique o processo de dados a todas as linhas do conjunto de dados usando um loop for()

  • 772

Eu tenho esse dataframe vazio

new_df<-structure(list(id = c("R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", 
"R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", 
"R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", 
"R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", 
"R_88j7lG37gLfxk22", "R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", 
"R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", 
"R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", 
"R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", 
"R_6DK8lERVf8lSQf4"), choice = c(0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 
1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1), low_env = c(NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA), mid_env = c(NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA), high_env = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), low_eth = c(NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA), mid_eth = c(NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA), high_eth = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), 
    `low_pri($25)` = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), 
    `mid_pri($75)` = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), 
    `high_pri($125)` = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, 
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA
    )), row.names = c(NA, 24L), class = "data.frame")

e com os dados e código acima preencho metade dele com base na primeira linha do longconjunto de dados. Como posso usar um for()loop para aplicar esse método ao restante das linhas do longconjunto de dados que preencherão a outra metade?

long<-structure(list(id = c("R_88j7lG37gLfxk22", "R_6DK8lERVf8lSQf4"
), t1_choice = c("2", "3"), t2_choice = c("1", "3"), t3_choice = c("1", 
"2"), t4_choice = c("2", "1"), t1_p1_env = c("high_env", "mid_env"
), t1_p1_eth = c("low_eth", "mid_eth"), t1_p1_pri = c("$125", 
"$25"), t1_p2_env = c("mid_env", "high_env"), t1_p2_eth = c("high_eth", 
"low_eth"), t1_p2_pri = c("$25", "$75"), t1_p3_env = c("low_env", 
"low_env"), t1_p3_eth = c("mid_eth", "low_eth"), t1_p3_pri = c("$75", 
"$75"), t2_p1_env = c("high_env", "mid_env"), t2_p1_eth = c("low_eth", 
"high_eth"), t2_p1_pri = c("$75", "$125"), t2_p2_env = c("mid_env", 
"low_env"), t2_p2_eth = c("mid_eth", "low_eth"), t2_p2_pri = c("$125", 
"$75"), t2_p3_env = c("mid_env", "high_env"), t2_p3_eth = c("mid_eth", 
"high_eth"), t2_p3_pri = c("$75", "$75"), t3_p1_env = c("high_env", 
"mid_env"), t3_p1_eth = c("high_eth", "mid_eth"), t3_p1_pri = c("$125", 
"$125"), t3_p2_env = c("mid_env", "high_env"), t3_p2_eth = c("low_eth", 
"low_eth"), t3_p2_pri = c("$25", "$25"), t3_p3_env = c("low_env", 
"low_env"), t3_p3_eth = c("high_eth", "high_eth"), t3_p3_pri = c("$25", 
"$75"), t4_p1_env = c("low_env", "high_env"), t4_p1_eth = c("low_eth", 
"low_eth"), t4_p1_pri = c("$75", "$125"), t4_p2_env = c("high_env", 
"mid_env"), t4_p2_eth = c("mid_eth", "mid_eth"), t4_p2_pri = c("$125", 
"$25"), t4_p3_env = c("low_env", "low_env"), t4_p3_eth = c("high_eth", 
"mid_eth"), t4_p3_pri = c("$25", "$125")), row.names = c(NA, 
-2L), class = c("tbl_df", "tbl", "data.frame"))

#working
# Loop through the first three rows of new_df
for (i in 1:3) {
  # Extracting the required values from long1 for each row
  env <- long[1,][paste0("t1_p", i, "_env")][1]
  eth <- long[1,][paste0("t1_p", i, "_eth")][1]
  pri <- long[1,][paste0("t1_p", i, "_pri")][1]
  
  # Matching values from long[1,] to new_df columns in the corresponding row
  new_df[i, "low_env"] <- as.numeric(env == "low_env")
  new_df[i, "mid_env"] <- as.numeric(env == "mid_env")
  new_df[i, "high_env"] <- as.numeric(env == "high_env")
  new_df[i, "low_eth"] <- as.numeric(eth == "low_eth")
  new_df[i, "mid_eth"] <- as.numeric(eth == "mid_eth")
  new_df[i, "high_eth"] <- as.numeric(eth == "high_eth")
  new_df[i, "low_pri($25)"] <- as.numeric(pri == "$25")
  new_df[i, "mid_pri($75)"] <- as.numeric(pri == "$75")
  new_df[i, "high_pri($125)"] <- as.numeric(pri == "$125")
}

# Loop through the second three rows of new_df
for (i in 1:3) {
  # Extracting the required values from long[1,] for each row
  env <- long[1,][paste0("t2_p", i, "_env")][1]
  eth <- long[1,][paste0("t2_p", i, "_eth")][1]
  pri <- long[1,][paste0("t2_p", i, "_pri")][1]
  
  # Matching values from long[1,] to new_df columns in the corresponding row
  new_df[i + 3, "low_env"] <- as.numeric(env == "low_env")
  new_df[i + 3, "mid_env"] <- as.numeric(env == "mid_env")
  new_df[i + 3, "high_env"] <- as.numeric(env == "high_env")
  new_df[i + 3, "low_eth"] <- as.numeric(eth == "low_eth")
  new_df[i + 3, "mid_eth"] <- as.numeric(eth == "mid_eth")
  new_df[i + 3, "high_eth"] <- as.numeric(eth == "high_eth")
  new_df[i + 3, "low_pri($25)"] <- as.numeric(pri == "$25")
  new_df[i + 3, "mid_pri($75)"] <- as.numeric(pri == "$75")
  new_df[i + 3, "high_pri($125)"] <- as.numeric(pri == "$125")
  # Adjusting the choice column
  new_df[i + 3, "choice"] <- as.numeric(long[1,][paste0("t2_choice")][1] == i)
}
  # Loop through the second three rows of new_df
  for (i in 1:3) {
    # Extracting the required values from long[1,] for each row
    env <- long[1,][paste0("t3_p", i, "_env")][1]
    eth <- long[1,][paste0("t3_p", i, "_eth")][1]
    pri <- long[1,][paste0("t3_p", i, "_pri")][1]
    
    # Matching values from long[1,] to new_df columns in the corresponding row
    new_df[i + 6, "low_env"] <- as.numeric(env == "low_env")
    new_df[i + 6, "mid_env"] <- as.numeric(env == "mid_env")
    new_df[i + 6, "high_env"] <- as.numeric(env == "high_env")
    new_df[i + 6, "low_eth"] <- as.numeric(eth == "low_eth")
    new_df[i + 6, "mid_eth"] <- as.numeric(eth == "mid_eth")
    new_df[i + 6, "high_eth"] <- as.numeric(eth == "high_eth")
    new_df[i + 6, "low_pri($25)"] <- as.numeric(pri == "$25")
    new_df[i + 6, "mid_pri($75)"] <- as.numeric(pri == "$75")
    new_df[i + 6, "high_pri($125)"] <- as.numeric(pri == "$125")
    # Adjusting the choice column
    new_df[i + 6, "choice"] <- as.numeric(long[1,][paste0("t3_choice")][1] == i)
  }
for (i in 1:3) {
  # Extracting the required values from long[1,] for each row
  env <- long[1,][paste0("t4_p", i, "_env")][1]
  eth <- long[1,][paste0("t4_p", i, "_eth")][1]
  pri <- long[1,][paste0("t4_p", i, "_pri")][1]
  
  # Matching values from long[1,] to new_df columns in the corresponding row
  new_df[i + 9, "low_env"] <- as.numeric(env == "low_env")
  new_df[i + 9, "mid_env"] <- as.numeric(env == "mid_env")
  new_df[i + 9, "high_env"] <- as.numeric(env == "high_env")
  new_df[i + 9, "low_eth"] <- as.numeric(eth == "low_eth")
  new_df[i + 9, "mid_eth"] <- as.numeric(eth == "mid_eth")
  new_df[i + 9, "high_eth"] <- as.numeric(eth == "high_eth")
  new_df[i + 9, "low_pri($25)"] <- as.numeric(pri == "$25")
  new_df[i + 9, "mid_pri($75)"] <- as.numeric(pri == "$75")
  new_df[i + 9, "high_pri($125)"] <- as.numeric(pri == "$125")
  

  # Adjusting the choice column
  new_df[i + 9, "choice"] <- as.numeric(long[1,][paste0("t4_choice")][1] == i)
}

resultado esperado

insira a descrição da imagem aqui

  • 3 3 respostas
  • 94 Views

3 respostas

  • Voted
  1. Best Answer
    jay.sf
    2024-01-07T23:38:42+08:002024-01-07T23:38:42+08:00

    Sua abordagem não parece divertida no momento. Em vez disso, você pode atribuir dados mais favoráveis names​​(ou seja, vezes como um sufixo em vez do formato de prefixo estranho) reshapeduas vezes ao formato longo desejado e usá-los model.matrixpara obter a codificação one-hot. Não tenho certeza de como você obteve a variável de escolha, já que a codificou, mas você saberá disso. Para obter todos os níveis, precisamos type.convert(as.is=FALSE)obter factors e definir contrastscomo FALSE.

    > names(long)[-1] <- 
    +   strsplit(names(long)[-1], '_') |>
    +   sapply(\(x) paste(paste(c(rev(x[-1])), collapse='_'), x[1], sep='.'))
    > res <- reshape(as.data.frame(long), varying=-1, direction='l') |>
    +   reshape(direction='l', varying=-(1:3), new.row.names=1:1e9, sep='_') |>
    +   type.convert(as.is=FALSE)
    > cbind(res[1:3], model.matrix(~ 0 + env + eth + pri, res, 
    +                              contrasts.arg = list(eth=contrasts(res$eth, contrasts=FALSE),
    +                                                   pri=contrasts(res$pri, contrasts=FALSE))))
                      id time choice envhigh_env envlow_env envmid_env ethhigh_eth ethlow_eth ethmid_eth pri$125 pri$25 pri$75
    1  R_88j7lG37gLfxk22   p1      2           1          0          0           0          1          0       1      0      0
    2  R_6DK8lERVf8lSQf4   p1      3           0          0          1           0          0          1       0      1      0
    3  R_88j7lG37gLfxk22   p1      1           1          0          0           0          1          0       0      0      1
    4  R_6DK8lERVf8lSQf4   p1      3           0          0          1           1          0          0       1      0      0
    5  R_88j7lG37gLfxk22   p1      1           1          0          0           1          0          0       1      0      0
    6  R_6DK8lERVf8lSQf4   p1      2           0          0          1           0          0          1       1      0      0
    7  R_88j7lG37gLfxk22   p1      2           0          1          0           0          1          0       0      0      1
    8  R_6DK8lERVf8lSQf4   p1      1           1          0          0           0          1          0       1      0      0
    9  R_88j7lG37gLfxk22   p2      2           0          0          1           1          0          0       0      1      0
    10 R_6DK8lERVf8lSQf4   p2      3           1          0          0           0          1          0       0      0      1
    11 R_88j7lG37gLfxk22   p2      1           0          0          1           0          0          1       1      0      0
    12 R_6DK8lERVf8lSQf4   p2      3           0          1          0           0          1          0       0      0      1
    13 R_88j7lG37gLfxk22   p2      1           0          0          1           0          1          0       0      1      0
    14 R_6DK8lERVf8lSQf4   p2      2           1          0          0           0          1          0       0      1      0
    15 R_88j7lG37gLfxk22   p2      2           1          0          0           0          0          1       1      0      0
    16 R_6DK8lERVf8lSQf4   p2      1           0          0          1           0          0          1       0      1      0
    17 R_88j7lG37gLfxk22   p3      2           0          1          0           0          0          1       0      0      1
    18 R_6DK8lERVf8lSQf4   p3      3           0          1          0           0          1          0       0      0      1
    19 R_88j7lG37gLfxk22   p3      1           0          0          1           0          0          1       0      0      1
    20 R_6DK8lERVf8lSQf4   p3      3           1          0          0           1          0          0       0      0      1
    21 R_88j7lG37gLfxk22   p3      1           0          1          0           1          0          0       0      1      0
    22 R_6DK8lERVf8lSQf4   p3      2           0          1          0           1          0          0       0      0      1
    23 R_88j7lG37gLfxk22   p3      2           0          1          0           1          0          0       0      1      0
    24 R_6DK8lERVf8lSQf4   p3      1           0          1          0           0          0          1       1      0      0
    

    Dados:

    > dput(long)
    structure(list(id = c("R_88j7lG37gLfxk22", "R_6DK8lERVf8lSQf4"
    ), t1_choice = c("2", "3"), t2_choice = c("1", "3"), t3_choice = c("1", 
    "2"), t4_choice = c("2", "1"), t1_p1_env = c("high_env", "mid_env"
    ), t1_p1_eth = c("low_eth", "mid_eth"), t1_p1_pri = c("$125", 
    "$25"), t1_p2_env = c("mid_env", "high_env"), t1_p2_eth = c("high_eth", 
    "low_eth"), t1_p2_pri = c("$25", "$75"), t1_p3_env = c("low_env", 
    "low_env"), t1_p3_eth = c("mid_eth", "low_eth"), t1_p3_pri = c("$75", 
    "$75"), t2_p1_env = c("high_env", "mid_env"), t2_p1_eth = c("low_eth", 
    "high_eth"), t2_p1_pri = c("$75", "$125"), t2_p2_env = c("mid_env", 
    "low_env"), t2_p2_eth = c("mid_eth", "low_eth"), t2_p2_pri = c("$125", 
    "$75"), t2_p3_env = c("mid_env", "high_env"), t2_p3_eth = c("mid_eth", 
    "high_eth"), t2_p3_pri = c("$75", "$75"), t3_p1_env = c("high_env", 
    "mid_env"), t3_p1_eth = c("high_eth", "mid_eth"), t3_p1_pri = c("$125", 
    "$125"), t3_p2_env = c("mid_env", "high_env"), t3_p2_eth = c("low_eth", 
    "low_eth"), t3_p2_pri = c("$25", "$25"), t3_p3_env = c("low_env", 
    "low_env"), t3_p3_eth = c("high_eth", "high_eth"), t3_p3_pri = c("$25", 
    "$75"), t4_p1_env = c("low_env", "high_env"), t4_p1_eth = c("low_eth", 
    "low_eth"), t4_p1_pri = c("$75", "$125"), t4_p2_env = c("high_env", 
    "mid_env"), t4_p2_eth = c("mid_eth", "mid_eth"), t4_p2_pri = c("$125", 
    "$25"), t4_p3_env = c("low_env", "low_env"), t4_p3_eth = c("high_eth", 
    "mid_eth"), t4_p3_pri = c("$25", "$125")), row.names = c(NA, 
    -2L), class = c("tbl_df", "tbl", "data.frame"))
    
    • 4
  2. Umar
    2024-01-08T02:33:28+08:002024-01-08T02:33:28+08:00
    I think here is the answer
    new_df<-structure(list(id = c("R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", 
                                  "R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", 
                                  "R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", 
                                  "R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", 
                                  "R_88j7lG37gLfxk22", "R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", 
                                  "R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", 
                                  "R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", 
                                  "R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", 
                                  "R_6DK8lERVf8lSQf4"), choice = c(0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 
                                                                   1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1), low_env = c(NA, NA, 
                                                                                                                          NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
                                                                                                                          NA, NA, NA, NA, NA, NA), mid_env = c(NA, NA, NA, NA, NA, NA, 
                                                                                                                                                               NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
                                                                                                                                                               NA, NA), high_env = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
                                                                                                                                                                                     NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), low_eth = c(NA, 
                                                                                                                                                                                                                                                          NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
                                                                                                                                                                                                                                                          NA, NA, NA, NA, NA, NA, NA), mid_eth = c(NA, NA, NA, NA, NA, 
                                                                                                                                                                                                                                                                                                   NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
                                                                                                                                                                                                                                                                                                   NA, NA, NA), high_eth = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, 
                                                                                                                                                                                                                                                                                                                             NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), 
                           `low_pri($25)` = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
                                              NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), 
                           `mid_pri($75)` = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
                                              NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), 
                           `high_pri($125)` = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, 
                                                NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA
                           )), row.names = c(NA, 24L), class = "data.frame")
    
    
    long<-structure(list(id = c("R_88j7lG37gLfxk22", "R_6DK8lERVf8lSQf4"
    ), t1_choice = c("2", "3"), t2_choice = c("1", "3"), t3_choice = c("1", 
                                                                       "2"), t4_choice = c("2", "1"), t1_p1_env = c("high_env", "mid_env"
                                                                       ), t1_p1_eth = c("low_eth", "mid_eth"), t1_p1_pri = c("$125", 
                                                                                                                             "$25"), t1_p2_env = c("mid_env", "high_env"), t1_p2_eth = c("high_eth", 
                                                                                                                                                                                         "low_eth"), t1_p2_pri = c("$25", "$75"), t1_p3_env = c("low_env", 
                                                                                                                                                                                                                                                "low_env"), t1_p3_eth = c("mid_eth", "low_eth"), t1_p3_pri = c("$75", 
                                                                                                                                                                                                                                                                                                               "$75"), t2_p1_env = c("high_env", "mid_env"), t2_p1_eth = c("low_eth", 
                                                                                                                                                                                                                                                                                                                                                                           "high_eth"), t2_p1_pri = c("$75", "$125"), t2_p2_env = c("mid_env", 
                                                                                                                                                                                                                                                                                                                                                                                                                                    "low_env"), t2_p2_eth = c("mid_eth", "low_eth"), t2_p2_pri = c("$125", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   "$75"), t2_p3_env = c("mid_env", "high_env"), t2_p3_eth = c("mid_eth", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               "high_eth"), t2_p3_pri = c("$75", "$75"), t3_p1_env = c("high_env", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       "mid_env"), t3_p1_eth = c("high_eth", "mid_eth"), t3_p1_pri = c("$125", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       "$125"), t3_p2_env = c("mid_env", "high_env"), t3_p2_eth = c("low_eth", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    "low_eth"), t3_p2_pri = c("$25", "$25"), t3_p3_env = c("low_env", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           "low_env"), t3_p3_eth = c("high_eth", "high_eth"), t3_p3_pri = c("$25", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            "$75"), t4_p1_env = c("low_env", "high_env"), t4_p1_eth = c("low_eth", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        "low_eth"), t4_p1_pri = c("$75", "$125"), t4_p2_env = c("high_env", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                "mid_env"), t4_p2_eth = c("mid_eth", "mid_eth"), t4_p2_pri = c("$125", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               "$25"), t4_p3_env = c("low_env", "low_env"), t4_p3_eth = c("high_eth", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          "mid_eth"), t4_p3_pri = c("$25", "$125")), row.names = c(NA, 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   -2L), class = c("tbl_df", "tbl", "data.frame"))
    
    
    
    library(dplyr)
    
    # Modify column names in long
    names(long)[-1] <- strsplit(names(long)[-1], '_') %>%
      sapply(function(x) paste(paste(c(rev(x[-1])), collapse='_'), x[1], sep='.'))
    
    # Reshape long dataset
    res <- long %>%
      as.data.frame() %>%
      reshape(varying=-1, direction='long') %>%
      reshape(direction='long', varying=-(1:3), new.row.names=1:1e9, sep='_')
    
    # Manually create dummy variables for env, eth, and pri
    env_dummy <- model.matrix(~ 0 + env, res, contrasts = FALSE)
    eth_dummy <- model.matrix(~ 0 + eth, res, contrasts = FALSE)
    pri_dummy <- model.matrix(~ 0 + pri, res, contrasts = FALSE)
    
    # Combine the original columns with the dummy variables
    model_matrix <- cbind(res[1:3], env_dummy, eth_dummy, pri_dummy)
    
    # Display the result
    print(model_matrix)
    
    print(model_matrix)
                      id time choice envhigh_env envlow_env envmid_env ethhigh_eth ethlow_eth ethmid_eth pri$125
    1  R_88j7lG37gLfxk22   p1      2           1          0          0           0          1          0       1
    2  R_6DK8lERVf8lSQf4   p1      3           0          0          1           0          0          1       0
    3  R_88j7lG37gLfxk22   p1      1           1          0          0           0          1          0       0
    4  R_6DK8lERVf8lSQf4   p1      3           0          0          1           1          0          0       1
    5  R_88j7lG37gLfxk22   p1      1           1          0          0           1          0          0       1
    6  R_6DK8lERVf8lSQf4   p1      2           0          0          1           0          0          1       1
    7  R_88j7lG37gLfxk22   p1      2           0          1          0           0          1          0       0
    8  R_6DK8lERVf8lSQf4   p1      1           1          0          0           0          1          0       1
    9  R_88j7lG37gLfxk22   p2      2           0          0          1           1          0          0       0
    10 R_6DK8lERVf8lSQf4   p2      3           1          0          0           0          1          0       0
    11 R_88j7lG37gLfxk22   p2      1           0          0          1           0          0          1       1
    12 R_6DK8lERVf8lSQf4   p2      3           0          1          0           0          1          0       0
    13 R_88j7lG37gLfxk22   p2      1           0          0          1           0          1          0       0
    14 R_6DK8lERVf8lSQf4   p2      2           1          0          0           0          1          0       0
    15 R_88j7lG37gLfxk22   p2      2           1          0          0           0          0          1       1
    16 R_6DK8lERVf8lSQf4   p2      1           0          0          1           0          0          1       0
    17 R_88j7lG37gLfxk22   p3      2           0          1          0           0          0          1       0
    18 R_6DK8lERVf8lSQf4   p3      3           0          1          0           0          1          0       0
    19 R_88j7lG37gLfxk22   p3      1           0          0          1           0          0          1       0
    20 R_6DK8lERVf8lSQf4   p3      3           1          0          0           1          0          0       0
    21 R_88j7lG37gLfxk22   p3      1           0          1          0           1          0          0       0
    22 R_6DK8lERVf8lSQf4   p3      2           0          1          0           1          0          0       0
    23 R_88j7lG37gLfxk22   p3      2           0          1          0           1          0          0       0
    24 R_6DK8lERVf8lSQf4   p3      1           0          1          0           0          0          1       1
       pri$25 pri$75
    1       0      0
    2       1      0
    3       0      1
    4       0      0
    5       0      0
    6       0      0
    7       0      1
    8       0      0
    9       1      0
    10      0      1
    11      0      0
    12      0      1
    13      1      0
    14      1      0
    15      0      0
    16      1      0
    17      0      1
    18      0      1
    19      0      1
    20      0      1
    21      1      0
    22      0      1
    23      1      0
    24      0      0
    
    • 1
  3. Umar
    2024-01-07T23:51:17+08:002024-01-07T23:51:17+08:00

    Você pode usar dplyr

    library(dplyr)
    
    # Modify column names in long
    names(long)[-1] <- strsplit(names(long)[-1], '_') %>%
      sapply(function(x) paste(paste(c(rev(x[-1])), collapse='_'), x[1], sep='.'))
    
    # Reshape long dataset
    res <- long %>%
      as.data.frame() %>%
      reshape(varying=-1, direction='long') %>%
      reshape(direction='long', varying=-(1:3), new.row.names=1:1e9, sep='_')
    
    # Create a model matrix
    model_matrix <- cbind(res[1:3], model.matrix(~ 0 + env + eth + pri, res))
    
    # Display the result
    print(model_matrix)
    
    id time choice envhigh_env envlow_env envmid_env ethlow_eth ethmid_eth pri$25 pri$75
    1  R_88j7lG37gLfxk22   p1      2           1          0          0          1          0      0      0
    2  R_6DK8lERVf8lSQf4   p1      3           0          0          1          0          1      1      0
    3  R_88j7lG37gLfxk22   p1      1           1          0          0          1          0      0      1
    4  R_6DK8lERVf8lSQf4   p1      3           0          0          1          0          0      0      0
    5  R_88j7lG37gLfxk22   p1      1           1          0          0          0          0      0      0
    6  R_6DK8lERVf8lSQf4   p1      2           0          0          1          0          1      0      0
    7  R_88j7lG37gLfxk22   p1      2           0          1          0          1          0      0      1
    8  R_6DK8lERVf8lSQf4   p1      1           1          0          0          1          0      0      0
    9  R_88j7lG37gLfxk22   p2      2           0          0          1          0          0      1      0
    10 R_6DK8lERVf8lSQf4   p2      3           1          0          0          1          0      0      1
    11 R_88j7lG37gLfxk22   p2      1           0          0          1          0          1      0      0
    12 R_6DK8lERVf8lSQf4   p2      3           0          1          0          1          0      0      1
    13 R_88j7lG37gLfxk22   p2      1           0          0          1          1          0      1      0
    14 R_6DK8lERVf8lSQf4   p2      2           1          0          0          1          0      1      0
    15 R_88j7lG37gLfxk22   p2      2           1          0          0          0          1      0      0
    16 R_6DK8lERVf8lSQf4   p2      1           0          0          1          0          1      1      0
    17 R_88j7lG37gLfxk22   p3      2           0          1          0          0          1      0      1
    18 R_6DK8lERVf8lSQf4   p3      3           0          1          0          1          0      0      1
    19 R_88j7lG37gLfxk22   p3      1           0          0          1          0          1      0      1
    20 R_6DK8lERVf8lSQf4   p3      3           1          0          0          0          0      0      1
    21 R_88j7lG37gLfxk22   p3      1           0          1          0          0          0      1      0
    22 R_6DK8lERVf8lSQf4   p3      2           0          1          0          0          0      0      1
    23 R_88j7lG37gLfxk22   p3      2           0          1          0          0          0      1      0
    24 R_6DK8lERVf8lSQf4   p3      1           0          1          0          0          1      0      0
    

    oi, mas se eu executar isso

    library(dplyr)
    
    # Modify column names in long
    names(long)[-1] <- strsplit(names(long)[-1], '_') %>%
      sapply(function(x) paste(paste(c(rev(x[-1])), collapse='_'), x[1], sep='.'))
    
    # Reshape long dataset
    res <- long %>%
      as.data.frame() %>%
      reshape(varying=-1, direction='long') %>%
      reshape(direction='long', varying=-(1:3), new.row.names=1:100, sep='_')
    
    # Ensure all combinations of env, eth, and pri are present
    all_combinations <- expand.grid(env = unique(res$env), eth = unique(res$eth), pri = c("$25", "$75", "$125"))
    
    # Merge with res to fill missing combinations with NA
    res <- merge(all_combinations, res, all = TRUE)
    
    # Convert 'pri' to factor with appropriate levels
    res$pri <- factor(res$pri, levels = c("$25", "$75", "$125"))
    res$eth <- factor(res$pri, levels = c("$25", "$75", "$125"))
    
    # Create a model matrix manually including dummy variables for pri
    model_matrix <- cbind(res[1:3], model.matrix(~ 0 + env + eth + pri - 1, res))
    
    # Display the result
    print(model_matrix)
    View(model_matrix)
    env      eth  pri envhigh_env envmid_env envlow_env ethmid_eth ethhigh_eth pri$75 pri$125
    1  high_env  low_eth  $25           1          0          0          0           0      0       0
    2  high_env  low_eth  $75           1          0          0          0           0      1       0
    3  high_env  low_eth  $75           1          0          0          0           0      1       0
    4  high_env  low_eth $125           1          0          0          0           0      0       1
    5  high_env  low_eth $125           1          0          0          0           0      0       1
    6  high_env  mid_eth  $25           1          0          0          1           0      0       0
    7  high_env  mid_eth  $75           1          0          0          1           0      1       0
    8  high_env  mid_eth $125           1          0          0          1           0      0       1
    9  high_env high_eth  $25           1          0          0          0           1      0       0
    10 high_env high_eth  $75           1          0          0          0           1      1       0
    11 high_env high_eth $125           1          0          0          0           1      0       1
    12  mid_env  low_eth  $25           0          1          0          0           0      0       0
    13  mid_env  low_eth  $75           0          1          0          0           0      1       0
    14  mid_env  low_eth $125           0          1          0          0           0      0       1
    15  mid_env  mid_eth  $25           0          1          0          1           0      0       0
    16  mid_env  mid_eth  $25           0          1          0          1           0      0       0
    17  mid_env  mid_eth  $75           0          1          0          1           0      1       0
    18  mid_env  mid_eth $125           0          1          0          1           0      0       1
    19  mid_env  mid_eth $125           0          1          0          1           0      0       1
    20  mid_env high_eth  $25           0          1          0          0           1      0       0
    21  mid_env high_eth  $75           0          1          0          0           1      1       0
    22  mid_env high_eth $125           0          1          0          0           1      0       1
    23  low_env  low_eth  $25           0          0          1          0           0      0       0
    24  low_env  low_eth  $75           0          0          1          0           0      1       0
    25  low_env  low_eth  $75           0          0          1          0           0      1       0
    26  low_env  low_eth  $75           0          0          1          0           0      1       0
    27  low_env  low_eth $125           0          0          1          0           0      0       1
    28  low_env  mid_eth  $25           0          0          1          1           0      0       0
    29  low_env  mid_eth  $75           0          0          1          1           0      1       0
    30  low_env  mid_eth $125           0          0          1          1           0      0       1
    31  low_env high_eth  $25           0          0          1          0           1      0       0
    32  low_env high_eth  $25           0          0          1          0           1      0       0
    33  low_env high_eth  $75           0          0          1          0           1      1       0
    34  low_env high_eth $125           0          0          1          0           1      0       1
    

    outras duas consultas foram respondidas, mas ainda estão faltando, acho que não será capaz de cobrir todos os níveis, você pode ver em um caso que está chegando na 24ª linha e, neste caso, está chegando na 34ª linha, mas não consigo retificar mais

    • 0

relate perguntas

  • Adicionar número de série para atividade de cópia ao blob

  • A fonte dinâmica do empacotador duplica artefatos

  • Selecione linhas por grupo com 1s consecutivos

  • Lista de chamada de API de gráfico subscritoSkus estados Privilégios insuficientes enquanto os privilégios são concedidos

  • Função para criar DFs separados com base no valor da coluna

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle?

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Quando devo usar um std::inplace_vector em vez de um std::vector?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Martin Hope
    Aleksandr Dubinsky Por que a correspondência de padrões com o switch no InetAddress falha com 'não cobre todos os valores de entrada possíveis'? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer Quando devo usar um std::inplace_vector em vez de um std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB Por que o GCC gera código que executa condicionalmente uma implementação SIMD? 2024-02-17 06:17:14 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve