我有以下示例数据框:
item<-c("A","B")
Type<-c("403P","1200C")
test_df<-data.frame(item, Type)
> test_df
item Type
1 A 403P
2 B 1200C
然后我将 test_df$Type 分成两列:
test_df$split_type<-strsplit(test_df$Type, "(?=[A-Za-z])(?<=[0-9])|(?=[0-9])(?<=[A-Za-z])", perl=TRUE)
test_df$split_type<-do.call(rbind, test_df$split_type)|>
data.frame()|>
rename(A = X1, B = X2)
新数据框如下:
> test_df
item Type split_type.A split_type.B
1 A 403P 403 P
2 B 1200C 1200 C
尝试使用新数据框进行过滤:
test_df%>%
filter(item=="A")%>%
select(item,split_type.A)
显示以下错误消息:
Error in `select()`:
! Can't subset columns that don't exist.
x Column `split_type.A` doesn't exist.
Run `rlang::last_trace()` to see where the error occurred.
请问我在分裂过程中是否做错了什么?欢迎所有意见和想法。谢谢。
谢谢@Jon Spring,我尝试使用你的方法,效果非常好。
> test_df
item Type
1 A 403P
2 B 1200C
> test_df<-test_df |> tidyr::separate(Type, into = c("A", "B"), sep = "(?<=[0-9])(?=[A-Za-z])")
> test_df%>%
+ filter(item=="A")%>%
+ select(item,A)
item A
1 A 403