R:从字符串向量中提取字符到数据框行

问题描述 投票:0回答:1

我有一个数据框,其中有一列,一个单词列表。我想从每个单词中提取字符并将其存储为数据框中的位置列。

例如,如果数据框定义如下:

words <- c('which', 'there', 'their', 'would') 
words <- as.data.frame(words)  

我希望它最后看起来像这样:

第一个位置 第二个位置 第三个位置 第四个位置 第五位置
哪个 w h c h
那里 t h e r e
他们的 t h e r
w o l d

到目前为止我所拥有的是:

position <- c("first_pos", "second_pos", "third_pos", "fourth_pos", "fifth_pos")
words[position] <- NA
dismantled <- str_split(words$words,"")

这会拆除单词并创建我需要的列。但是,我可以使用一些帮助来用字母填充列的行。

r dataframe substring
1个回答
2
投票

我们可以在

separate
中每个字符之间的空格后使用
words
:

library(tidyverse)
words %>%
  mutate(words1 =  sub("\\s+$", "", gsub('(.{1})', '\\1 ', words))) %>% 
  separate(words1, into = paste0(1:5, "_pos"))
  words 1_pos 2_pos 3_pos 4_pos 5_pos
1 which     w     h     i     c     h
2 there     t     h     e     r     e
3 their     t     h     e     i     r
4 would     w     o     u     l     d
© www.soinside.com 2019 - 2024. All rights reserved.