在基数 R 中,strsplit
命令将对这种形式的向量进行操作,但会生成一个列表,您必须进一步简化该列表。
In the tidyr
包里有一个separate
函数将保留事物的数据框架性质。对于这个用例来说,这可能更可取。
例如
> library(tidyr)
> a <- data.frame(x=1:3, y=c("a|b|c", "b|c|d", "d|e|f"))
> a
x y
1 1 a|b|c
2 2 b|c|d
3 3 d|e|f
> separate(a, y, c("a","b","c"), '\\|')
x a b c
1 1 a b c
2 2 b c d
3 3 d e f
为了充实strsplit
稍微解决一下,你将不得不使用一个有点尴尬的组合cbinds
到那里
> cbind(a, do.call(cbind, strsplit(as.character(a$y), "\\|")))
x y 1 2 3
1 1 a|b|c a b d
2 2 b|c|d b c e
3 3 d|e|f c d f
编辑:还应该注意,如果您使用tidyr
方法,你将不得不递归地使用它,可能与unite
,以获得完整的行为。就像是
df <- separate(df, col, c("type", "subtype", "rawclass"), "\\|")
df <- separate(df, rawclass, c("class", "subclass"), "_")
df <- unite(df, sp, type, subtype, sep="|")
假设原始列名为col
,以及最终标题的虚构名称。