R 按模式将一列拆分为多列 [英] R Split a column into multiple column by pattern

查看:32
本文介绍了R 按模式将一列拆分为多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数据框列中的数字和字符分开 d.df:

I want to separate the digits and character in a column of a dataframe d.df:

col1 
ab 12 14 56
xb 23 234 2342 2
ad 23 45

预期输出:

col1   col2
ab     12 14 56
xb     23 234 2342 2
ad     23 45

我知道它会与此类似,但我不确定分隔符

I recognize it will be something similar to this, but I'm not sure about the separators

t <- as.data.frame(str_match(d$col1,"^(.*)"))

我尝试了很多方法,结果是:

I tried many methods and the output was:

col1      col2      
a         b 12 14 56
x         b  23 234 2342 2
a         d  23 45

推荐答案

这里的方法会有很大不同,具体取决于这实际上是您的字符串的样子还是只是一个示例.如果它们总是两个字母和数字,你可以substring:

The approach here will vary significantly depending on whether this is actually how your strings look like or just an example. If they are always two letters and numbers, you can substring:

> df <- data.frame(col1 = c("ab 12 14 56", "xb 23 234 2342 2", "ad 23 45"))
> 
> df$col1.1 <- sapply(df$col1, substring, 0, 2)
> 
> df$col1.2 <- sapply(df$col1, substring, 3)
> 
> df
              col1 col1.1         col1.2
1      ab 12 14 56     ab       12 14 56
2 xb 23 234 2342 2     xb  23 234 2342 2
3         ad 23 45     ad          23 45

如果字符串的长度和位置发生变化,正则表达式可能更适合.使用基本的 R 方法,您只能提取数字或字母(保留空格):

If the length and positions of the strings change, regex might be better suited. Using a base R approach, you can extract only the numbers or letters (keeping the white spaces):

> df <- data.frame(col1 = c("ab 12 14 56", "xb 23 234 2342 2", "ad 23 45"))
> df$col1.1 <- sapply(regmatches(df$col1, gregexpr("[a-zA-Z]", df$col1)), paste, collapse = "")
> df$col1.2 <- sapply(regmatches(df$col1, gregexpr("[0-9]\s*", df$col1)), paste, collapse = "")
> df
              col1 col1.1        col1.2
1      ab 12 14 56     ab      12 14 56
2 xb 23 234 2342 2     xb 23 234 2342 2
3         ad 23 45     ad         23 45

这篇关于R 按模式将一列拆分为多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆