我试图在R中创建两个独立的专栏.我遇到的问题是,根据观测类型的不同,年份并不与前一个专栏分开.
数据框中的一些名字只是名字,另一些名字则有名字和姓氏.我正在try 让Name
显示第一个和第一个/最后一个,并将Year
与当前的Name
列分开.
虚假数据=员工和他们开始工作的年份
创建数据框
library(tidyverse)
dat <- tibble(Name = c("Percy Vere (2020)", "Ginger Plant (2017)", "Perry (2019)",
"Pat Thettick (2020)", "Samuel (2022)", "Fay Daway (2008)",
"Greg (2022)", "Simon Sais (2011)"))
# A tibble: 8 x 1
Name
<fct>
1 Percy Vere (2020)
2 Ginger Plant (2017)
3 Perry (2019)
4 Pat Thettick (2020)
5 Samuel (2022)
6 Fay Daway (2008)
7 Greg (2022)
8 Simon Sais (2011)
try 将该列拆分为两列:Name
和Year
dat %>%
select_all() %>%
separate(col = Name, into = c('Name', 'Year')) %>% # sep = ',' and ';' does not create a fix
tibble()
# A tibble: 8 x 2
Name Year
<chr> <chr>
1 Percy Vere
2 Ginger Plant
3 Perry 2019
4 Pat Thettick
5 Samuel 2022
6 Fay Daway
7 Greg 2022
8 Simon Sais
Warning message:
Expected 2 pieces. Additional pieces discarded in 8 rows [1, 2, 3, 4, 5, 6, 7, 8].