r - 多列数据框
问题描述
我有一个带有单列的数据框,我想在 R 上拆分它。它包含日期、文本和数字。我想将我的文本保留在一个列中,所以我不能用空格分隔。我的想法是在单词之间添加一个破折号,然后用空格分隔。但是如果不删除单词的第一个和最后一个字母,我不知道该怎么做。
有没有人有任何想法:
- 在所有字母的单词之间添加破折号
- 以任何其他方式分隔在多个列中
这是我拥有的数据框类型:
tab <- data.frame(c1 = c("21.03.2016 This amasingly interesting text 2'000.50 3'000.60",
"22.03.2016 This other terrific text 5'000.54 6'000.90"))
#This is what I would like to obtain
tab1 <- data.frame(c1 = c("21.03.2016", "22.03.2016"),
c2 = c("This amasingly interesting text", "This other terrific text"),
c3 = c( "2'000.50", "5'000.54"),
c4 = c( "3'000.60", "6'000.90"))
#This is what I did to add dash
tab <- gsub("[A-z] [A-z]","_", tab$c1)
tab <- data.frame(tab)
library(stringr)
tab <- data.frame(str_split_fixed(tab$tab, " ", 4))
#This is pretty much what I want unless that some letters are missing
tab$X2 <- gsub("_"," ",tab$X2)
解决方案
您可以尝试tidyr::extract
函数并提供regex
参数以按预期方式将文本与列分开。
一种这样的尝试可以是:
library(tidyverse)
tab %>% extract(col = c1, into = c("C1","C2","C3","C4"),
regex = "([0-9.]+)\\s([A-Za-z ]+)\\s([0-9.']+)\\s(.*)")
# C1 C2 C3 C4
# 1 21.03.2016 This amasingly interesting text 2'000.50 3'000.60
# 2 22.03.2016 This other terrific text 5'000.54 6'000.90
正则表达式解释:
`([0-9.]+)` - Look for `0-9` or `.` and make 1st group for 1st column `\\s` - Leave a space `([A-Za-z ]+)` - Look for `alphabetic` or `space` characters. Group for 2nd column `\\s` - Leave a space ([0-9.'] - Look for `0-9`, `.` or `'` and make group for 3rd column `\\s` - Leave a space (.*) - Anything at the end to make group for 4th column
推荐阅读
- windows - 如何使用 Go 在 Windows 上获取文件所有者?
- javascript - 为什么我在 vuex 商店中的初始状态未定义?
- mysql - 拆分字符串字段后添加行号
- python - 在python中导入图像
- python - 在 Python 中连接 C 结构
- matlab - 如何分别计算每个尺度级别的二维逆平稳小波变换?
- firebase - Firebase 功能的源图支持?
- javascript - SVG 和文本在 Safari 上不起作用
- django - 在博客文章中添加下一个/上一个按钮
- javascript - 我在 es6 中编写代码并使用了调用方法,但其他参数未通过它显示未定义