Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a value to character string

Tags:

r

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.

like image 619
user2716568 Avatar asked Jun 01 '15 00:06

user2716568


People also ask

How do you assign a value to a character?

To assign int value to a char variable in Java would consider the ASCII value and display the associated character/ digit. Here, we have a char. char val; Now assign int value to it.

How do you assign a value to a string?

String assignment is performed using the = operator and copies the actual bytes of the string from the source operand up to and including the null byte to the variable on the left-hand side, which must be of type string. You can create a new variable of type string by assigning it an expression of type string.

How do you assign a character to a string?

We can convert char to String in java using String. valueOf(char) method of String class and Character. toString(char) method of Character class.

How do you set a character value in R?

The assign() function in R can be used to assign values to variables. where: x: A variable name, given as a character string. value: The value(s) to be assigned to x.


3 Answers

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
like image 188
Jota Avatar answered Sep 29 '22 17:09

Jota


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"))
like image 43
Tim Biegeleisen Avatar answered Sep 29 '22 15:09

Tim Biegeleisen


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)]
like image 40
jalapic Avatar answered Sep 29 '22 15:09

jalapic