您可以使用separate
函数从tidyr包(将我的评论提升为答案)。您指定两个列名并使用extra = "merge"
参数,您确保第一个空格之后的所有内容都放入第二列:
library(tidyr)
separate(mydf, V1, c("nr","text"), sep = " ", extra = "merge")
# or:
mydf %>% separate(V1, c("nr","text"), sep = " ", extra = "merge")
you get:
nr text
1 0001 This is text for 0001
2 0002 This has spaces in between
3 0003 Yet this is only supposed to be two columns
4 0009 Why didnt they just comma delimit you may ask?
5 0010 Or even use quotations?
6 001 Who knows
7 0012 But now Im here with his file
8 0013 And hoping someone has an elegant solution?
使用数据:
mydf <- structure(list(V1 = structure(c(1L, 2L, 3L, 4L, 6L, 5L, 7L, 8L),
.Label = c("0001 This is text for 0001", "0002 This has spaces in between",
"0003 Yet this is only supposed to be two columns", "0009 Why didnt they just comma delimit you may ask?",
"001 Who knows", "0010 Or even use quotations?", "0012 But now Im here with his file", "0013 And hoping someone has an elegant solution?"), class = "factor")),
.Names = "V1", class = "data.frame", row.names = c(NA,-8L))