在R中具有数字数据到分类数据

时间:2019-11-04 22:35:16

标签: r

我有调查数据,其中涉及参与者的回答。

我的数据格式为4 3 2 3 3 3 3 3 3 3 3 4 3 3 3 3 3 3 2 3 3

或者,以dput格式:

c(4, 3, 2, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 3, 3, 2, 3, 3)

但是我想将它们归类为

strongly disagree = 1 
disagree = 2 
agree = 3 
strongly agree = 4 

,以便在进行直方图绘制时可以使用不同的颜色。

我尝试使用此方法

datatat = survey$Q1A 
catsurvey <- cut(datatat, breaks =c(0,2,3,4),  labels=c("Disagree", "Agree", "Strongly Agree"))    
hist(datatat , main="Distribution of Player Ratings", xlab="Responses", border = "black" ,col = c("blue", "red", "green"))  

1 个答案:

答案 0 :(得分:1)

尝试以下方法。由于您不想创建数据框,因此我为您发布的数据取了另一个名字。

x <- scan(text = '4 3 2 3 3 3 3 3 3 3 4 3 3 3 3 3 3 2 3 3')
labs <- c('strongly disagree',
          'disagree',
          'agree',
          'strongly agree')

datatat <- factor(x, levels = 1:4, labels = labs)
tbl <- table(datatat)

barplot(tbl[tbl != 0],
     main = "Distribution of Player Ratings", 
     xlab = "Responses", 
     border = "black", col = c("blue", "red", "green"))

enter image description here