Reputation: 33
I have multiple columns with variables I need to reverse-code. Let's say my column names are A,B,C,D and each column has a mix of values from 1-4. I am trying to recode all the 4's as 1's, 3's as 2's. etc.
I am able to do it like this:
`dataNew$A <- as.numeric(dataNew$A)
levels(dataNew$A)[levels(dataNew$A)=="1"] <- "4"
levels(dataNew$A)[levels(dataNew$A)=="2"] <- "3"
levels(dataNew$A)[levels(dataNew$A)=="3"] <- "2"
levels(dataNew$A)[levels(dataNew$A)=="2"] <- "1"`
Then I could repeat for columns B, C, D
However, I'm wondering if there is a cleaner way to do this where I can change multiple numbers or multiple columns and numbers at once, rather than individually writing the above code for each column/number combination.
Upvotes: 1
Views: 552
Reputation: 5956
If those are the only data frame values, then you can actually do something very simple, stealing @Michael Dewar's sample data code.
df <- data.frame(
A = sample(1:4, 50, replace = TRUE),
B = sample(1:4, 50, replace = TRUE),
C = sample(1:4, 50, replace = TRUE),
D = sample(1:4, 50, replace = TRUE)
)
head(df)
#> A B C D
#> 1 3 4 4 3
#> 2 2 3 3 1
#> 3 1 4 1 2
#> 4 4 1 2 1
#> 5 4 3 3 2
#> 6 1 2 2 1
df <- 5 - df
head(df)
#> A B C D
#> 1 2 1 1 2
#> 2 3 2 2 4
#> 3 4 1 4 3
#> 4 1 4 3 4
#> 5 1 2 2 3
#> 6 4 3 3 4
If your newData
is not numeric and you want to convert, you can easily convert into a numeric data frame using:
as.data.frame(sapply(newData, as.numeric))
However, since it appears your data might be factors, you should be careful how those are converted to as.numeric
. See this thread for the details, but you might want to do:
as.data.frame(sapply(newData, \(x) as.numeric(levels(x)[x])))
Upvotes: 3
Reputation: 3318
How about:
library(tidyverse)
dataNew <- tibble(A = sample(1:4, 50, replace = TRUE),
B = sample(1:4, 50, replace = TRUE),
C = sample(1:4, 50, replace = TRUE),
D = sample(1:4, 50, replace = TRUE))
dataNew %>%
mutate(across(A:D, ~ 5-.))
Upvotes: 3