如何在R中将连续变量转换为分类

时间:2019-07-05 02:52:35

标签: r function variables cat

我有一个名为clean_test_master2的df,您可以访问df Here

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的列是调和还是离散

我找到了答案here

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等不同的分析(请参见问题here)。

我发现本教程here解释了如何使用名为cat的函数,该函数创建了一个单独的df,但我确实希望保持原样。我需要在df的列中进行更改。

2 个答案:

答案 0 :(得分:1)

在Tidyverse中,您可以使用dplyr::mutate_at()将多列的类别更改为因子:

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)

答案 1 :(得分:0)

对于要转换为因子的每一列,只需修改sapply行即可使用as.factor而不是is.factor,并将其写回该变量名。

例如:

clean_test_master2$stim_ending_t <- sapply(clean_test_master2$stim_ending_t, as.factor)