为了账号安全,请及时绑定邮箱和手机立即绑定

将数据框架字符串列拆分为多个列

将数据框架字符串列拆分为多个列

千万里不及你 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条经验 获得超6个赞

加入强制性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 关注
  • 666 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信