[英]How to convert continuous variable to a categorical in r
我有一個名為clean_test_master2的df,您可以在此處訪問df
stim_ending_t visbility soundvolume Opening_text m sd coefVar
<dbl> <dbl> <dbl> <chr> <dbl> <dbl> <dbl>
1 1 0 0 Now focus on the Image 1.70 1.14 0.670
2 1 0 0 Now focus on the Sound 1.57 0.794 0.504
3 1 0 1 Now focus on the Image 1.55 1.09 0.701
4 1 0 1 Now focus on the Sound 1.77 0.953 0.540
5 1 1 0 Now focus on the Image 1.38 0.859 0.621
6 1 1 0 Now focus on the Sound 1.59 0.706 0.444
7 1.5 0 0 Now focus on the Image 1.86 0.718 0.387
8 1.5 0 0 Now focus on the Sound 2.04 0.713 0.350
9 1.5 0 1 Now focus on the Image 1.93 1.00 0.520
10 1.5 0 1 Now focus on the Sound 2.14 0.901 0.422
我運行此函數is.factor
來查看我df的列是調和還是離散
我在這里找到答案
f <- sapply(clean_test_master2, is.factor)
> f
stim_ending_t visbility soundvolume Opening_text m sd coefVar
FALSE FALSE FALSE FALSE FALSE FALSE FALSE
我不確定這里的錯誤是什么意思? 以及如何檢查我的列是連續的,離散的還是分類的
問:這里的重要問題是如何將stim_ending_t
轉換為分類的,以便我可以進行ANOVA等不同的分析(請在此處查看此問題)。
我在這里找到了本教程,該教程說明了如何使用名為cat
的函數,該函數創建了一個單獨的df,但我確實希望保持原樣。 我需要在df的列中進行更改。
在Tidyverse中,可以使用dplyr::mutate_at()
將多列的類更改為factor:
clean_test_master2 <- clean_test_master2 %>%
mutate_at(c("stim_ending_t", "visbility", "soundvolume", "Opening_text"), as.factor)
sapply(clean_test_master2, is.factor)
> sapply(clean_test_master2, is.factor)
stim_ending_t visbility soundvolume Opening_text m sd coefVar
TRUE TRUE TRUE TRUE FALSE FALSE FALSE
如果您具有適合單個類別的值范圍,則可能需要分別定義每列(使用factor(x, levels = y, labels = z)
。
您只需將要轉換為因子的每一列修改為sapply
行,以使用as.factor
而不是is.factor
並將其寫回該變量名。
例如:
clean_test_master2$stim_ending_t <- sapply(clean_test_master2$stim_ending_t, as.factor)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.