亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將數據框架字符串列拆分為多個列

將數據框架字符串列拆分為多個列

千萬里不及你 2019-05-28 17:40:39
將數據框架字符串列拆分為多個列我想要獲取表格的數據before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))  attr          type1    1   foo_and_bar2   30 foo_and_bar_23    4   foo_and_bar4    6 foo_and_bar_2并使用split()上面的列“ type”來得到這樣的東西:  attr type_1 type_21    1    foo    bar2   30    foo  bar_23    4    foo    bar4    6    foo  bar_2我提出了一些令人難以置信的復雜問題,涉及某種形式的apply工作,但我已經錯了。這似乎太復雜了,不是最好的方式。我可以使用strsplit如下,但不清楚如何將其恢復到數據框中的2列。> strsplit(as.character(before$type),'_and_')[[1]][1] "foo" "bar"[[2]][1] "foo"   "bar_2"[[3]][1] "foo" "bar"[[4]][1] "foo"   "bar_2"謝謝你的任何指示。我還沒有完全理解R列表。
查看完整描述

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


查看完整回答
反對 回復 2019-05-28
?
qq_花開花謝_0

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)]


查看完整回答
反對 回復 2019-05-28
  • 4 回答
  • 0 關注
  • 744 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號