In a recent project, I have quite a big data frame. And I'd like to reprogram certain variables using a vector that I defined earlier.
I know there are many other ways to recode the data, but I was wondering if I could use the vector because it seems like an elegant solution.
df <- data.frame(
A = c(1,2,2,1),
B = c(1,1,1,2),
C = c(2,2,1,2)
)
vector <- c(
"A",
"B"
)
Consider this example. Here I have created a vector, which consists of 2 Names in the Data set. Can I now use this vector to reprogram the data frame? E.g. I'd like to change all '1' to a '0' in the columns 'A' and 'B'.
I tried this:
df[df[,vector]==1] <- 0
Yet this code only works, when i define the Vector like this:
vector <- c(
"A",
"B",
"C"
)
Therefore, when it includes all the variables in the data frame.
If I use the same code, but the vector does only include 'A' and 'B', i get the following error:
Error in `[<-.data.frame`(`*tmp*`, df[, vector] == 2, value = 1) : unsupported matrix index in replacement
Do you have an Idea on how this might work?
Kind regards