0

在 R 中,我有两个数据框,我需要用第二个 df 重塑第一个数据框。

使用实际数据

工作表“Plan2”

https://docs.google.com/spreadsheets/d/1jkxik-QWz0kQYskQQXgaP0TXT7TsBLjp5RHSqtEw0pU/edit?usp=sharing

if(!require("FrF2")) install.packages("FrF2") ; library(FrF2)

df <- EXPERIMENTO_SALA <- read_excel("mypath/EXPERIMENTO SALA.xlsx", 
                           col_types = c("numeric", "numeric", "numeric", 
                                         "numeric", "numeric", "numeric", 
                                         "numeric", "numeric", "numeric"))


view(df)
print.data.frame(df)

另一个数据框是:

plan.person = FrF2(nfactors = 5,
               resolution = 5,
               replications = 2,
               randomize = FALSE,
               factor.names = list(
                 pH = c(3, 9),
                 Temp = c(5, 30),
                 Dose = c(0.05, 0.5),
                 Conc = c(50, 350),
                 Speed = c(100, 200)
               ))

view(plan.person)

请注意,数据框是相似的。这是因为我正在复制一个学习来练习 R 软件进行实验分析。最大的区别是 em 'df' 我对这个实验有三个响应,并且组织的行也有差异。

我需要重塑数据框'df'以使其等于数据框'plan.person',但是我需要三帧数据'plan.person'(plan.person1,plan.person2,plan.person3 ),一个用于分析中的每个响应(SMO 去除百分比、CO 去除百分比、Bright-Edge 80 去除百分比),这些响应位于数据帧“df”中。

请问,我该怎么做?

** 我通过一个较小的例子展示了一个使用玩具数据的更一般的例子。

if(!require("FrF2")) install.packages("FrF2") ; library(FrF2)
if(!require("truncnorm")) install.packages("truncnorm") ; library(truncnorm)

plan.person = FrF2(nfactors = 3,
               resolution = 3,
               replications = 2,
               randomize = FALSE,
               factor.names = list(
                 Temp = c(5, 30),
                 Conc = c(50, 350),
                 Speed = c(100, 200)
               ))

Temperatura <- c(5, 5, 30, 30, 5, 5, 30, 30)
Concentracao <- c(350, 50, 350, 50, 350, 50, 350, 50)
Velocidade <- c(100, 200, 200, 100, 100, 200, 200, 100)

remov_SMO <- rtruncnorm(n=8, a=0, mean=61.16, sd=31.32)
remov_CO <- rtruncnorm(n=8, a=0, mean=79, sd=24.17)
remov_BE <- rtruncnorm(n=8, a=0, mean=71.43, sd=29.61)


df <- data.frame(Temperatura, Concentracao, Velocidade, remov_SMO,
            remov_CO, remov_BE)


view(df)
view(plan.person)

在这个较小的示例中,我需要根据 Temperatura (= Temp)、Concentracao (= Conc) 和 Velocidade (= Speed ) 信息,以组织实验响应,以便您可以继续使用 FrF2 包。

https://i.imgur.com/DQBHQNi.png

4

1 回答 1

1

由于顺序很重要,并且您有重复的组合,因此我认为对两个数据框进行排序,绑定它们,然后返回到原始顺序会更容易:

df <- data.frame(Temperatura,
                 Concentracao,
                 Velocidade,
                 remov_SMO, remov_CO, remov_BE)


reorder_ids <- do.call(order, as.list(plan.person))
plan_ordered <- plan.person[reorder_ids,]
df_ordered <- df[do.call(order, as.list(df[, 1:3])),]

new_plan <- data.frame(plan_ordered, df_ordered[, -(1:3)])
new_plan <- new_plan[reorder_ids,] # restore original order
attributes(new_plan) <- attributes(plan.person)

我认为new_plan应该有你想要的,但你可能需要调整列名。

编辑:我会特别注意输出属性,在我看来,plan.person添加了很多附加FrF2功能,其他功能可能取决于它们。

于 2018-05-21T18:57:05.510 回答