[英]How to specify two variable as equal levels of a factor?
在我的數據集中,我有一個名為Condition
的變量。 我將此建模為具有兩個級別的因素: Control
和Treatment
。 在同一個數據框中,我還有變量: Fish1
、 Fish2
、 Frechfires1
、 Frenchfries2
。 我想將 model 這些'Ordinalvariables'
作為Fish
高於fries
的治療組的水平,同時,我想保持Fish1
和Fish2
的水平相同,並且對於 fries1&2-all 進行Treatment
(這是變量Condition
的水平)。
適合混合 model: Health~Condition() 考慮到魚和薯條的影響
Condition SubNum Trial Num_Fish1 Num_Fish2 Num_Fries1 Num_Fries2 Health
Treatment 1 1 1 1 2 1 3
Treatment 1 2 0 3 4 1 5
Control 2 1 0 0 0 0 4
Control 2 2 0 0 0 0 5
如果我正確理解了這個問題,那么您真的只需要有序的因子水平“魚”和“薯條”,並在數字 1 和 2 提供的每個級別內進一步區分。
使用以下數據:
df <- read.table(text = "Condition SubNum Trial Num_Fish1 Num_Fish2 Num_Fries1 Num_Fries2 Health
Treatment 1 1 1 1 2 1 3
Treatment 1 2 0 3 4 1 5
Control 2 1 0 0 0 0 4
Control 2 2 0 0 0 0 5", header = T)
我會使用tidyr::gather()
將列名Num_*
放入變量product
中,然后將產品類型和產品編號分別提取為有序和無序因子。
library(tidyr)
library(dplyr)
library(stringr)
df_out <- df %>%
gather("product", "product_value", -c(Condition:Trial, Health)) %>%
mutate(product_num = factor(str_match(product, "\\d")),
product = ordered(str_remove_all(product, "Num_|\\d"),
levels = c("Fries", "Fish")
)
)
您最終應該得到一個如下所示的數據框,您可以使用它來靈活地比較“Fish”和“Fries”(序數),或“Fish 1”和“Fish 2”(在這兩種情況下都只是“Fish”,所以本質上是名義上的)等。我將product_num
轉換為一個因子,而不是一個 integer 向量,以避免可能由整數的內在順序引起的任何混淆。 根據您的建模策略,您可能仍需要對數據進行子集化和/或重新分級。
# A tibble: 16 x 7
Condition SubNum Trial Health product product_value product_num
<fct> <int> <int> <int> <ord> <int> <fct>
1 Treatment 1 1 3 Fish 1 1
2 Treatment 1 2 5 Fish 0 1
3 Control 2 1 4 Fish 0 1
4 Control 2 2 5 Fish 0 1
5 Treatment 1 1 3 Fish 1 2
6 Treatment 1 2 5 Fish 3 2
7 Control 2 1 4 Fish 0 2
8 Control 2 2 5 Fish 0 2
9 Treatment 1 1 3 Fries 2 1
10 Treatment 1 2 5 Fries 4 1
11 Control 2 1 4 Fries 0 1
12 Control 2 2 5 Fries 0 1
13 Treatment 1 1 3 Fries 1 2
14 Treatment 1 2 5 Fries 1 2
15 Control 2 1 4 Fries 0 2
16 Control 2 2 5 Fries 0 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.