繁体   English   中英

将字符串拆分为数据框

[英]Split String to data frame

我正在尝试在R中拆分单行文本并将其存储在数据框中。

例如。 文本如下:

hello-world;1|(good)night world;2|...

预计将成为:

V1    V2
hello-world    1
(good)night world    2

为了实现这一点:我首先在'\\'上分割初始文本。 因此,我将tidyr与分开使用。

library(tidyr)
as.data.frame(str) %>% separate(str, into=c("V1"), sep='\\|')
1 hello-world;1
#Warning message:
#Too many values at 1 locations: 1

我怀疑第一次分裂的问题是- 我该如何解决这个问题?

这个怎么样?

library(tidyverse)

text <- c("hello-world;1|(good)night world;2")

df_text <- data.frame(a = unlist(strsplit(text, "|", fixed = T)))

df_split_text <- separate(df_text, a, c("V1", "V2"), sep = ";")

如果要通过tidyverse进行此tidyverse则需要使用unnest使其变长,然后separateseparate ,即

libraary(tidyverse)

data.frame(v1 = 'hello-world;1|(good)night world;2|') %>% 
       mutate(v1 = strsplit(as.character(v1), '\\|')) %>% 
       unnest(v1) %>% 
       separate(v1, into = c('v1', 'v2'), sep = ';')

# A tibble: 2 x 2
#                 v1    v2
#*             <chr> <chr>
#1       hello-world     1
#2 (good)night world     2

我们知道@ udden2903用tidyverse给出了最好的答案,但是这个base R应该起作用。 替换| 使用\\n ,然后使用read.table进行读取

read.table(text=gsub("[|]", "\n", text), header = FALSE, sep=";", stringsAsFactors= FALSE)
#                 V1 V2
#1       hello-world  1
#2 (good)night world  2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM