我有一个数据框,列中的单词用单个空格分隔。我想把它分成三种类型,如下所示。数据框如下所示。
Text
one of the
i want to
我想把它分成如下。
Text split1 split2 split3
one of the one one of of the
我能够获得第一名。无法弄清楚其他两个。
我的代码获得split1:
new_data$split1<-sub(" .*","",new_data$Text)
想出了split2:
df$split2 <- gsub(" [^ ]*$", "", df$Text)
答案 0 :(得分:0)
可能有更优雅的解决方案。这有两个选择:
使用ngrams
:
library(dplyr); library(tm)
df %>% mutate(splits = strsplit(Text, "\\s+")) %>%
mutate(split1 = lapply(splits, `[`, 1)) %>%
mutate(split2 = lapply(splits, function(words) ngrams(words, 2)[[1]]),
split3 = lapply(splits, function(words) ngrams(words, 2)[[2]])) %>%
select(-splits)
Text split1 split2 split3
1 one of the one one, of of, the
2 i want to i i, want want, to
手动提取两克:
df %>% mutate(splits = strsplit(Text, "\\s+")) %>%
mutate(split1 = lapply(splits, `[`, 1)) %>%
mutate(split2 = lapply(splits, `[`, 1:2),
split3 = lapply(splits, `[`, 2:3)) %>%
select(-splits)
Text split1 split2 split3
1 one of the one one, of of, the
2 i want to i i, want want, to
<强>更新强>:
使用正则表达式,我们可以使用gsub的后向引用。
Split2:
gsub("((.*)\\s+(.*))\\s+(.*)", "\\1", df$Text)
[1] "one of" "i want"
Split3:
gsub("(.*)\\s+((.*)\\s+(.*))", "\\2", df$Text)
[1] "of the" "want to"
答案 1 :(得分:0)
我们可以尝试使用gsub
。捕获一个或多个非空白区域(\\S+
)作为一组(在这种情况下有3个单词),然后在替换中,我们重新排列后向引用并插入一个分隔符(,
)用于使用read.table
转换为不同的列。
df1[paste0("split", 1:3)] <- read.table(text=gsub("(\\S+)\\s+(\\S+)\\s+(\\S+)",
"\\1,\\1 \\2,\\2 \\3", df1$Text), sep=",")
df1
# Text split1 split2 split3
#1 one of the one one of of the
#2 i want to i i want want to
df1 <- structure(list(Text = c("one of the", "i want to")),
.Names = "Text", class = "data.frame", row.names = c(NA, -2L))
答案 2 :(得分:0)
这是一个黑客的解决方案。
假设: - 你不关心两个单词之间的空格数。
> library(stringr)
> x<-c('one of the','i want to')
> strsplit(gsub('(\\S+)\\s+(\\S+)\\s+(.*)', '\\1 \\1 \\2 \\2 \\3', x), '\\s\\s+')
#[[1]]
#[1] "one" "one of" "of the"
#[[2]]
#[1] "i" "i want" "want to"