# Generate the difference between 3 different variables

I need help generating a new variable "Difference".
I have to complete this Task: Calculate a bivariate regression model with the difference regarding immigration as the independent variable. but to do so i have to generate the Variable "Difference". The variable should capture how much the stance on immigration differs between the chosen party and the individual's own position. For this, the stance of the party chosen by the person with their second vote in the 2021 federal election should be used for each individual.

i cant use the ifelse Function and will have to use case_when or mutate, but i just can´t get my code right.

This is my Code so far, but it doesn´t work:

``````d\$Difference <- mutate(d\$q8ba == "CDU" ~ abs(d\$q42b - d\$q43), d\$q8ba == "SPD" ~ abs(d\$q42d - d\$q43), d\$q8ba == "FDP" ~ abs(d\$q42e - d\$q43), d\$q8ba == "GRUENE" ~ abs(d\$q42f - d\$q43), d\$q8ba == "LINKE" ~ abs(d\$q42g - d\$q43), d\$q8ba == "AfD" ~ abs(d\$q42h - d\$q43), NA)

´´´
The Data that i have used is: https://search.gesis.org/research_data/ZA7700

``````

d\$q8ba <- set_na(d\$q8ba, na = -99:-71)
d\$q8ba <- set_na(d\$q8ba, na = 120:318)
d\$q8ba <- set_na(d\$q8ba, na = 326:810)
d\$q8ba <- set_na(d\$q8ba, na = 2:3)

d\$q43 <- set_na(d\$q43, na = -99:-71)

d\$q42b <- set_na(d\$q42b, na = -99:-71)
d\$q42d <- set_na(d\$q42d, na = -99:-71)
d\$q42e <- set_na(d\$q42e, na = -99:-71)
d\$q42f <- set_na(d\$q42f, na = -99:-71)
d\$q42g <- set_na(d\$q42g, na = -99:-71)
d\$q42h <- set_na(d\$q42h, na = -99:-71)

´´´´

I know, that most of the code, that i´ve done is simple and more complicated that needed. But can you help me generate a code to generate the variable "Difference"?

Thank you fore your help Hi, welcome to the forum

I think we need a see more of your code and some sample data.

A handy way to supply some sample data is the dput() function. In the case of a large dataset something like dput(head(mydata, 100)) should supply the data we need. Just do dput(mydata) where mydata is your data. Copy the output and paste it here.

For example you are doing something with the function `set_na()` but what package does it come from?

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.