本文介绍了如何使用 tidyr 将向量中字符串中的每个字符分成一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将向量中的每个字符串分成列,但我做不到!

I want to separate each string in the vector into columns but I can't do it!

library(tidyr)  
    library(dplyr)
    df <- data.frame(x = c("abe", "bas", "dds", "eer"))
    df %>% separate(x, c("A", "B", "C"), sep=1)

我想要的输出看起来像这样

The output I want looks like this

  A B C
1 a b e
2 b a s
3 d d s
4 e e r

那个 sep=1 对 2 个字符有效,但对 3 个字符无效.我希望像 sep="这样的正则表达式."或 sep="[a-z]" 也可以,但不行.

That sep=1 works for 2 characters but doesn't work for 3. I was hoping a regex like sep="." or sep="[a-z]" would work too but it doesn't.

这可能非常简单,但我是 R 的新手.有人可以帮忙吗!

This is probably super easy but I'm new to R. Won't someone please help!

推荐答案

您非常接近自己的解决方案.只需为 sep 参数添加第二个位置.

You were quite close with your own solution. Simply add a second position for the sep argument.

所以:

library(tidyr)  
library(dplyr)
df <- data.frame(x = c("abe", "bas", "dds", "eer"))
df %>% separate(x, c("A", "B", "C"), sep = c(1,2))

  A B C
1 a b e
2 b a s
3 d d s
4 e e r

这篇关于如何使用 tidyr 将向量中字符串中的每个字符分成一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 07:46