Assign value to character string

I have survey responses in my data.frame(Analysis) , which includes:

Q1 <- c("Agree", "Strongly Agree", "Disagree", "Neither", "Agree", "Neither")

I want to assign a meaning to each answer based on their level. For example, "Strongly Agree" gets 2, and "Agree" gets a grade of 1. My desired result would be:

Q1 <- c("Agree", "Strongly Agree", "Disagree", "Neither", "Agree", "Neither")
Q1_Score <- c(1, 2, -1, 0, 1, 0)

This seems like a simple question, but it's hard for me to find the answer!

Thanks.

+8
r
source share
3 answers

You can use the revalue from the revalue package to create a new factor column in your Analysis data frame with levels renamed:

 library(plyr) Analysis$Q1_Score <- revalue(Analysis$Q1, c("Strongly Agree"="2", "Agree"="1", "Neither"="0", "Disagree"="-1")) 
+5
source share

You can put values ​​and codes in a separate data frame, and then use match to get them in your main framework:

 dat <- data.frame(Q1,Q1_Score) Analysis$Q1_Score <- dat$Q1_Score[match(Analysis$Q1, dat$Q1)] 
+5
source share

You can arrange them accordingly in a factor variable, and then convert them to a numerical value like this:

 Q1 <- factor(Q1, levels=c("Disagree","Neither","Agree","Strongly Agree")) as.numeric(Q1)-2 #[1] 1 2 -1 0 1 0 

You subtract 2 because the lowest level coefficient is stored as 1, and you want the lower level to be -1.

Alternatively, a single line that returns a numeric variable instead of numbers:

 factor(Q1, levels=c("Disagree","Neither","Agree","Strongly Agree"), labels=c(-1,0,1,2)) #[1] 1 2 -1 0 1 0 #Levels: -1 0 1 2 
+2
source share

All Articles