I have variables named xa_1, xa_2, ..., xa_n that I want to change in certain ways.
- I want to create new variables named xa_n_ that I will perform these changes on
- Then I want to recode the values of these (categorical) variables, e.g. reversing a Likert scale
I have tried the following:
for(i in c(xa_1, xa_2, ..., xa_n) {
df$[i]_ <- df$[i] # I am sure I need to use paste() in some ways but I have been unable to figure it out
}
I tried this unsuccessfully:
a <- 1:n
for (i in seq_along(a)) {
df$paste(xa_,[i]_,sep="") <- df$paste(xa_,[i], sep="")
}
As you see, I have problems with basic functions and understanding of data manipulation in R. In short, I would like to manipulate a set of variables by combining two features of their name, that is their common core (xa_) and their identifying number (1, .., n).
Putting together all separate parts, what I would like to eventually figure out is a way to do the following:
for(i in c(xa_) {
for( j in 1:4) {
df$paste([i],[j]_, sep="") <- df$paste([i],[j],sep=") # Create a copy of existing variables that runs across variables and numbers
df$paste([i],[j]_, sep="") <- ifelse(df$paste([i],[j],sep=") == 1, 4, ifelse(df$paste([i],[j],sep=") == 2, 3, ifelse(df$paste([i],[j],sep=")== 3, 2, ifelse(df$paste([i],[j],sep=") == 4, 1, NA)))) # recode the new variables based on values in old variables
df$paste([i],[j],_, sep="") <- factor(paste([i],[j],_, sep=""), levels=c(1:4), labels=c("Something", "Something else", "Something else again", "Something else at last")) # Rename the values in the new variables and make them categorical
}
Hopefully this makes enough sense so that you understand what I mean:)
How about doing it in a
dplyr
way like this?Assume that your data frame looks like this:
The code above gives you:
Try the following code if you also want to keep those variables:
Output: