0

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?

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.