Almond
Almond

Reputation: 87

Split existing column to multiple new columns

I have a data frame like this:

original data frame

I would like this result:

expected result

I wrote this code:

test$statetwentyeighteen = test$state[test$year=="2018"]

but I get this wrong result:

wrong result

Can you please help see how to revise the code?


update:

I am having a new issue with this matter. when the original table is updated to this: updated data frame

this code no longer works

test %>% group_by(name) %>% mutate(state_twentyeighteen = state[year == 2018])

instead I get this error message:

Error: Column `state_twentyeighteen` must be length 3 (the group size) or one, not 2

Can you please see what revision should be done to the code?

Upvotes: 0

Views: 40

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389235

Using dplyr, you can do

library(dplyr)
test %>% group_by(name) %>% mutate(state_twentyeighteen = state[year == 2018])

and similarly with data.table

library(data.table)
setDT(test)[, state_twentyeighteen := state[year == 2018], name]

Upvotes: 1

Related Questions