1)假设 x 在最终使用时的注释中可重复定义read.table
如图所示。不使用正则表达式或包。
read.table(text = Table$Column, sep = "|", header = FALSE,
as.is = TRUE, fill = TRUE)[6]
giving:
V6
1 Gold
2 Silver
3 Silver
4 Iron
5 Copper
6 Iron
2)这种替代方案确实使用了正则表达式(问题要求不要使用正则表达式),但以防万一,这里有一个 tidyr 解决方案。请注意,它需要 tidyr 0.8.2 或更高版本,因为早期版本的 tidyr 不支持NA
in the into=
争论。
library(dplyr)
library(tidyr)
Table %>%
separate(Column, into = c(rep(NA, 5), "commodity"), sep = "\\|", extra = "drop")
giving:
commodity
1 Gold
2 Silver
3 Silver
4 Iron
5 Copper
6 Iron
3)这是另一个基本解决方案。鉴于 (1) 简单得多,它可能不是您想要的,但我想看看我们是否可以在基础中提出第二种不使用正则表达式的方法。请注意,如果split=
的论证strsplit
is ""
然后它被特殊处理,所以不是正则表达式。它创建一个列表,其每个组件都是单个字符的向量。每个这样的向量都被传递给匿名函数,该函数标记|
及其后面字段中的字符及其序号。然后我们取出对应于 5 的字符(第一个除外)|
)并使用将它们折叠在一起paste
.
data.frame(commodities = sapply(strsplit(Table$Column, ""), function(chars) {
wx <- which(cumsum(chars == "|") == 5)
paste(chars[seq(wx[2], tail(wx, 1))], collapse = "")
}), stringsAsFactors = FALSE)
giving:
commodities
1 Gold
2 Silver
3 Silver
4 Iron
5 Copper
6 Iron
Note
Table <- data.frame(Column = c("|1||KK|12|Gold||4K|",
"|1||Rst|E|Silver||13||",
"|1||RST|E|Silver||18||",
"|1||KK|Y|Iron|y|12||",
"|1||||Copper|Cpr|||E",
"|1||||Iron|||12|F"), stringsAsFactors = FALSE)