[英]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使用
dplyr
,你可以做
library(dplyr)
test %>% group_by(name) %>% mutate(state_twentyeighteen = state[year == 2018])
and similarly with data.table
与
data.table
类似
library(data.table)
setDT(test)[, state_twentyeighteen := state[year == 2018], name]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.