[英]R: Extracting charcters from string vectors to data frame rows
我有一个数据框,其中有一个列,一个单词列表。 我想从每个单词中提取字符并将其存储为数据框中的 position 列。 例如,如果 dataframe 定义如下:
words <- c('which', 'there', 'their', 'would')
words <- as.data.frame(words)
我希望它最后看起来像这样:
字 | first_pos | second_pos | third_pos | fourth_pos | fifth_pos |
---|---|---|---|---|---|
哪一个 | w | H | 一世 | c | H |
那里 | 吨 | H | 电子 | r | 电子 |
他们的 | 吨 | H | 电子 | 一世 | r |
将 | w | o | 你 | 升 | d |
到目前为止我所拥有的是:
position <- c("first_pos", "second_pos", "third_pos", "fourth_pos", "fifth_pos")
words[position] <- NA
dismantled <- str_split(words$words,"")
这会分解单词并创建我需要的列。 但是,我可以使用一些帮助来用字母填充列的行。
我们可以在words
中每个字符之间的空格后使用separate
符:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.