我有一个名为df的data.frame,其中一个名为Text的列由一些句子组成,我想添加一个新的名为Length的列,该列等于单词中的单词数文本列。因此,我的data.frame看起来像这样:
Text
1. First sentence.
2. Second sentence that is a bit longer.
3. Third.
4. Fourth one is the longest one with 9 words.
并且所需的data.frame应该看起来像这样:
Text Length
1. First sentence. 2
2. Second sentence that is a bit longer. 7
3. Third. 1
4. Fourth one is the longest one with 9 words. 9
这些是我的尝试:
df$Length <- length(do.call(strsplit(., " ")[[1]], as.list(df$Text)))
和
df$Length <- do.call(length(strsplit(., " ")[[1]]), as.list(df$Text))
请您帮助我了解我该怎么办?
您也可以使用purrr软件包:
df %>%
mutate(Length = purrr::map_dbl(Text, ~ length(strsplit(., " "))))