我需要通过字数将字符串分成两半(当有奇数个字时,中间字应出现在左侧和右侧)。我还需要知道每个字符串的哪一方来自。
my_question <- data.frame(string_id = c(001, 002, 003),
string = (c("how do I split", "how do I split this", "how do I split this string")))
my_answer <- data.frame(string_id = c(001, 002, 003, 001, 002, 003),
string = (c("how do", "how do I", "how do I", "I split", "I split this", "split this string")),
side = c("R", "R", "R", "L", "L", "L"))
我更喜欢使用 stringr / tidyverse / hadleyverse 。
答案 0 :(得分:1)
我们可以编写一些辅助函数来使这更容易
library(tidyverse)
word_split <- function(x, side="left", sep=" ") {
words <- strsplit(as.character(x), sep)
nwords <- lengths(words)
if(side=="left") {
start <- 1
end <- ceiling(nwords/2)
} else if (side=="right") {
start <- ceiling((nwords+1)/2)
end <- nwords
}
cw <- function(words, start, stop) paste(words[start:stop], collapse=sep)
pmap_chr(list(words, start, end), cw)
}
left_words <- function(..., side) word_split(..., side="left")
right_words <- function(..., side) word_split(..., side="right")
然后我们可以使用更传统的管道链来分享您想要的结果
my_question %>% mutate(L=left_words(string),
R=right_words(string)) %>%
select(-string) %>%
gather(side, string, L:R)
导致
string_id side string
1 1 L how do
2 2 L how do I
3 3 L how do I
4 1 R I split
5 2 R I split this
6 3 R split this string