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

发布于 2025-02-07 22:10:06 字数 1027 浏览 0 评论 0原文

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

例如,如果按这样的数据框架定义:

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

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

first_possecond_posthirth_posfourfirtth_pos fifth_posfifth_pos
whichth
thei r tt hee i rr e
单词whe i i i ie ir
hw w w w w w w到目前为止可以

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

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

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

I have a data frame which has one column, a list of words. I'd like to extract the characters from each word and have it stored as a position column in the data frame.

For example, if the dataframe is defined like this:

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

I'd like it to look like this at the end:

wordsfirst_possecond_posthird_posfourth_posfifth_pos
whichwhich
therethere
theirtheir
wouldwould

What I have so far is:

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

This dismantles the words and creates the columns I need. However, I could use some help filling the rows of the columns with the letters.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谈场末日恋爱 2025-02-14 22:10:06

我们可以在单词中的每个字符之间使用单独的

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

We could use separate after a space between each character in words:

library(tidyverse)
words %>%
  mutate(words1 =  sub("\\s+
quot;, "", 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文