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.
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.
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.
We can convert char to String in java using String. valueOf(char) method of String class and Character. toString(char) method of Character class.
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.
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
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"))
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With