简体   繁体   中英

Split existing column to multiple new columns

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?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM