Reputation: 87
I have a data frame like this:
I would like this result:
I wrote this code:
test$statetwentyeighteen = test$state[test$year=="2018"]
but I get this 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:
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
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