4 回答
TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超10個(gè)贊
另一種選擇是使用新的tidyr包。
library(dplyr)
library(tidyr)
before <- data.frame(
attr = c(1, 30 ,4 ,6 ),
type = c('foo_and_bar', 'foo_and_bar_2')
)
before %>%
separate(type, c("foo", "bar"), "_and_")
## attr foo bar
## 1 1 foo bar
## 2 30 foo bar_2
## 3 4 foo bar
## 4 6 foo bar_2
TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
加入強(qiáng)制性data.table解決方案
library(data.table) ## v 1.9.6+
setDT(before)[, paste0("type", 1:2) := tstrsplit(type, "_and_")]
before
# attr type type1 type2
# 1: 1 foo_and_bar foo bar
# 2: 30 foo_and_bar_2 foo bar_2
# 3: 4 foo_and_bar foo bar
# 4: 6 foo_and_bar_2 foo bar_2
我們也可以通過(guò)添加和參數(shù)來(lái)確保生成的列具有正確的類型并提高性能(因?yàn)樗皇钦嬲恼齽t表達(dá)式)type.convertfixed"_and_"
setDT(before)[, paste0("type", 1:2) := tstrsplit(type, "_and_", type.convert = TRUE, fixed = TRUE)]
- 4 回答
- 0 關(guān)注
- 762 瀏覽
添加回答
舉報(bào)
