在R.do中使用嵌套函数

问题描述 投票:0回答:1

我有一个名为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))

请您帮助我了解我该怎么办?

r dataframe strsplit
1个回答
0
投票

您也可以使用purrr软件包:

df %>%
 mutate(Length = purrr::map_dbl(Text, ~ length(strsplit(., " "))))
© www.soinside.com 2019 - 2024. All rights reserved.