有这样的数据框:
data.frame(text = c("separate1: and: more","another 20: 42")
Run Code Online (Sandbox Code Playgroud)
如何在每一行中使用第一个 : 进行分隔?预期输出示例
data.frame(text1 = c("separate1","another 20"), text2 = c("and: more","42")
Run Code Online (Sandbox Code Playgroud)
在base 中,您可以使用regexpr查找第一个的位置,该位置:可用于提取子字符串和trimws删除空格。
x <- c("separate1: and: more","another 20: 42")
i <- regexpr(":", x)
data.frame(text1 = trimws(substr(x, 1, i-1)), text2 = trimws(substring(x, i+1)))
# text1 text2
#1 separate1 and: more
#2 another 20 42
Run Code Online (Sandbox Code Playgroud)
library(reshape2)
df <- data.frame(text = c("separate1: and: more","another 20: 42")
colsplit(df$text, ":", c("text1", "text2"))
Run Code Online (Sandbox Code Playgroud)