4 回答

TA貢獻1777條經驗 獲得超10個贊
另一種選擇是使用新的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貢獻1835條經驗 獲得超7個贊
加入強制性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
我們也可以通過添加和參數來確保生成的列具有正確的類型并提高性能(因為它不是真正的正則表達式)type.convertfixed"_and_"
setDT(before)[, paste0("type", 1:2) := tstrsplit(type, "_and_", type.convert = TRUE, fixed = TRUE)]
- 4 回答
- 0 關注
- 744 瀏覽
添加回答
舉報