我有一個資料框,它有一個列,一個單詞串列。我想從每個單詞中提取字符并將其存盤為資料框中的位置列。例如,如果資料框是這樣定義的:
words <- c('which', 'there', 'their', 'would')
words <- as.data.frame(words)
我希望它最后看起來像這樣:
字 | first_pos | second_pos | 第三個位置 | 第四個位置 | 第五個位置 |
---|---|---|---|---|---|
哪個 | w | H | 一世 | C | H |
那里 | 噸 | H | e | r | e |
他們的 | 噸 | H | e | 一世 | r |
將 | w | ○ | 你 | l | d |
到目前為止,我所擁有的是:
position <- c("first_pos", "second_pos", "third_pos", "fourth_pos", "fifth_pos")
words[position] <- NA
dismantled <- str_split(words$words,"")
這會分解單詞并創建我需要的列。但是,我可以使用一些幫助來用字母填充列的行。
uj5u.com熱心網友回復:
我們可以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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/491329.html