Assign a value to character string

17,837

Solution 1

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

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

Solution 2

You could put the values and the codes in a separate dataframe and then use match to get them into your main dataframe :

dat <- data.frame(Q1,Q1_Score)

Analysis$Q1_Score <- dat$Q1_Score[match(Analysis$Q1, dat$Q1)]

Solution 3

You can order them appropriately in a factor variable, then convert to numeric like so:

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 factor level is stored as 1, and you want the lowest level to be -1.

Alternatively, a one-liner that returns a factor variable instead of numerics:

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
Share:
17,837

Related videos on Youtube

user2716568
Author by

user2716568

Updated on June 27, 2022

Comments

  • user2716568
    user2716568 almost 2 years

    I have responses to a survey in my data.frame(Analysis) that include:

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

    I wish to assign a value to each response, based upon their level. For example, "Strongly Agree" receives a 2 whilst "Agree" receives a score of 1. My desired output would be:

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

    This seems like an simple question but I am having difficulty in finding an answer!

    Thank you.

  • user2716568
    user2716568 almost 9 years
    I voted the answer to the use of the plyr package but I also like your answer using the base of R. Thank you.
  • thelatemail
    thelatemail almost 9 years
    Or even just c("Strongly Agree"=2, "Agree"=1, "Neither"=0, "Disagree"=-1)[Q1]

Related