Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
按tidyr和dplyr中的模式(单词)分隔_R_String_Dplyr_Tidyr - Fatal编程技术网

按tidyr和dplyr中的模式(单词)分隔

按tidyr和dplyr中的模式(单词)分隔,r,string,dplyr,tidyr,R,String,Dplyr,Tidyr,我有一个非常简单的需求:在dplyr管道链中将一列拆分为两个新列。这里的诀窍是使用特定的单词作为分隔符,而不是单个字符 数据: id elements 1 banana and apple 2 orange and lemon 3 house and flat 预期结果 id element1 element2 1 banana apple 2 orange lemon 3 house fl

我有一个非常简单的需求:在dplyr管道链中将一列拆分为两个新列。这里的诀窍是使用特定的单词作为分隔符,而不是单个字符

数据:

id    elements
1     banana and apple
2     orange and lemon
3     house and flat
预期结果

id    element1    element2
1      banana      apple
2      orange      lemon
3      house       flat
显然,tidyr::separate方法没有按预期工作(我的错)。通过单词“and”的第一个字母进行分隔

df %>% tidyr::separate(elements, into = c("element1","element2"), sep = "and")

我知道这可能可以通过其他动词实现,但我的主要目标是尽可能使用dplyr和tidyr来实现。

我们可以指定and前后的空格,以及删除它们

library(dplyr)
library(tidyr)
df %>%
   separate(elements, into = c('element1', 'element2'),
          sep = '\\s*and\\s*')
-输出

#  id element1 element2
#1  1   banana    apple
#2  2   orange    lemon
#3  3    house     flat
数据
df我们可以指定and前后的空格,也可以删除它们

library(dplyr)
library(tidyr)
df %>%
   separate(elements, into = c('element1', 'element2'),
          sep = '\\s*and\\s*')
-输出

#  id element1 element2
#1  1   banana    apple
#2  2   orange    lemon
#3  3    house     flat
数据
df你能
dput
你的数据吗?@Forge当你说不能按预期工作时不清楚?我得到了正确的输出。为了删除空格,我添加了
\\s*
。当你使用分隔符时,你能显示你的输出吗?它是用“and”中的第一个字母分隔的。“a”你能
dput
你的数据吗?@Forge当你说不能按预期工作时,它不清楚?我得到了正确的输出。为了删除空格,我添加了
\\s*
。当你使用分隔符时,你能显示你的输出吗?它是用“and”中的第一个字母分隔的。“a”