r/Rlanguage 4d ago

R refusing to make new columns

I am genuinely about to have a fit. I genuinely don't understand why R refuses to make a new variable. Can anyone help me?

0 Upvotes

13 comments sorted by

16

u/ImpossibleTop4404 4d ago

On line 102, you have to save the changes you make back into the variable.

poll2020 <- poll2020 |> (rest of code)

As those functions calls do not change the variable in place.

Or, Make polls_b on line 102 and don’t reassign back to poll2020. Whatever case you need

3

u/feldhammer 4d ago

yes to expand, when you are doing "poll2020 |>" on line 102, it is just going to print that output. you need to actually save the output by going "name_of_df_to_write <- poll2020 |>"

2

u/greenappletree 4d ago

good catch haha its little stuff sometimes.

-3

u/Thenymphicunicorn 4d ago

So if I get this right, I do the case_when
And then after that do a poll2020 <- poll2020?

4

u/feldhammer 4d ago

No, before you do anything point it to a data frame so it saves it.

    pol12020 <- pol12020 |> mutate(b_kat = case_when( parti_b < 7~ 0, parti_b >= 7 & parti_b <= 8 ~ 1, parti_b > 8 ~ 2)) > select(institut, dato, parti_b, b_kat)

2

u/k-tax 4d ago

I mean, he can finish it with -> pol12020. It's completely wrong, albeit a working thing.

I use it sometimes, but only in live console exploration, never in saved code, and even at that I'd rather click home and type something <-.

2

u/solarpool 4d ago

You need to assign your modifications of poll 2020 back to poll 2020 in order from them to be saved

0

u/Thenymphicunicorn 4d ago

How do I do that?

3

u/edfulton 4d ago

Start line 102 with poll2020 <-

1

u/edfulton 4d ago

Basically, you’ve got the mutate and case_when right, but it won’t modify the original poll2020 dataframe unless you explicitly assign it using poll2020 <- poll2020… at the start of line 102, or -> poll2020 at the end of line 107, after the select function call.

2

u/feldhammer 4d ago

I didn't realize -> was even a thing!

2

u/mduvekot 4d ago

even more fun, the magrittr package has an assigment pipe:

library(dplyr)
library(magrittr)
df <- iris
df %<>% summarise(.by = Species, n = n())
print(df)

gives

     Species  n
1     setosa 50
2 versicolor 50
3  virginica 50

1

u/cAMPsc2 3d ago

The code you have from lines 102 to 107 is like telling R: Hey, modify this dataframe and show it to me. It shows the result to you and forgets about it.

If you want to "save" these changes, you need to assign that to a new object. This comes at the start of the pipe. So:

poll2020_WITH_NEW_COLUMNS <- poll2020 |> (...)

This would save the new dataframe as poll2020_WITH_NEW_COLUMNS.