热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

将字符拆分为数据框中的两个变量-splitcharactersintotwovariablesindataframe

LetssayIhaveavectorofvariableslikethis:假设我有一个像这样的变量向量:>variable[1]A1A1A1

Let's say I have a vector of variables like this:

假设我有一个像这样的变量向量:

>variable
[1] "A1" "A1" "A1" "A1" "A2" "A2" "A2" "A2" "B1" "B1" "B1" "B1"

and I want to covert this into into a data frame like this:

我想把它转换成这样的数据框:

  treatment time
1         A    1
2         A    1
3         A    1
4         A    1
5         A    2
6         A    2
7         A    2
8         A    2
9         B    1
10        B    1
11        B    1
12        B    1

To that end, I used reshape2's colsplit function. It rquires a pattern to split the string, but I quickly realize there is no obvious pattern to split the two characters without any space. I tried "" and got the following results:

为此,我使用了reshape2的colsplit功能。它需要一个模式来分割字符串,但我很快意识到没有明显的模式来分割两个字符而没有任何空格。我试过“”并得到以下结果:

> colsplit(trialm$variable,"",names=c("treatment","time"))
   treatment time
1         NA   A1
2         NA   A1
3         NA   A1
4         NA   A1
5         NA   A2
6         NA   A2
7         NA   A2
8         NA   A2
9         NA   B1
10        NA   B1
11        NA   B1
12        NA   B1

I also tried a lookbehind or lookahead regular expression :

我也尝试过lookbehind或lookahead正则表达式:

>colsplit(trialm$variable,"(?<=\\w)",names=c("treatment","time"))
Error in gregexpr("(?<=\\w)", c("A1", "A1", "A1", "A1", "A2", "A2", "A2",  : 
  invalid regular expression '(?<=\w)', reason 'Invalid regexp'

but it gave me the above error. How can I solve this problem?

但它给了我上面的错误。我怎么解决这个问题?

9 个解决方案

#1


7  

substr is another way to do it.

substr是另一种方法。

> variable <- c(rep("A1", 4), rep("A2", 4), rep("B1", 4))
> data.frame(treatment=substr(variable, 1,1), time=as.numeric(substr(variable,2,2)))
   treatmen time
1         A    1
2         A    1
3         A    1
4         A    1
5         A    2
6         A    2
7         A    2
8         A    2
9         B    1
10        B    1
11        B    1
12        B    1

#2


9  

Update: 24 December 2017

Somewhere along the line, the "stringr" package (which is imported with "reshape2" and which is responsible for the splitting that takes place with colsplit) started to use "stringi" for several of its functions. Some behavior seems to have changed because of that.

沿着这条线的某个地方,“stringr”包(使用“reshape2”导入并负责使用colsplit进行拆分)开始使用“stringi”来实现其几个功能。由于这一点,一些行为似乎已经改变。

Using the current "reshape2" (and current "stringr" package), colsplit works the way you would have expected it to with your code:

使用当前的“reshape2”(以及当前的“stringr”包),colsplit的工作方式与您对代码的预期方式相同:

packageVersion("reshape2")
## [1] ‘1.4.3’
packageVersion("stringr")
## [1] ‘1.2.0’

colsplit(variable, "", names = c("treatment", "time"))
##    treatment time
## 1          A    1
## 2          A    1
## 3          A    1
## 4          A    1
## 5          A    2
## 6          A    2
## 7          A    2
## 8          A    2
## 9          B    1
## 10         B    1
## 11         B    1
## 12         B    1

Original Answer: 24 April 2013

If a pattern can be detected in your "variable" but there is no clean split character that can be used, then add one :)

如果可以在“变量”中检测到模式但是没有可以使用的干净分割字符,那么添加一个:)

library(reshape2)
variable <- c("A1", "A1", "A1", "A1", "A2", "A2", 
              "A2", "A2", "B1", "B1", "B1", "B1")
## Here, we add a "." between upper case letters and numbers
colsplit(gsub("([A-Z])([0-9])", "\\1\\.\\2", variable), 
         "\\.", c("Treatment", "Time"))
#    Treatment Time
# 1          A    1
# 2          A    1
# 3          A    1
# 4          A    1
# 5          A    2
# ::::: snip :::: #
# 11         B    1
# 12         B    1

Additional Options: 23 December 2017

My "splitstackshape" package has a single-purpose non-exported helper function called NoSep that can be used for this:

我的“splitstackshape”包有一个名为NoSep的单用途非导出辅助函数,可用于此:

splitstackshape:::NoSep(variable)
##    .var .time_1
## 1     A       1
## 2     A       1
## 3     A       1
## 4     A       1
## 5     A       2
## ::: snip :::: #
## 11    B       1
## 12    B       1

The "tidyverse" (specifically the "tidyr" package) has a couple of convenient functions for splitting values into different columns: separate and extract. separate has already been demonstrated by jazzuro, but the solution is very specific to this particular problem. Also, it generally works better with a delimiter. extract expects you to specify a regular expression with the groups you want to capture:

“tidyverse”(特别是“tidyr”包)有几个方便的功能,可以将值分成不同的列:单独和提取。 jazzuro已经证明了分离,但解决方案非常特定于这一特定问题。此外,它通常使用分隔符更好。 extract希望您指定包含要捕获的组的正则表达式:

library(tidyverse)
data.frame(variable) %>% 
  extract(variable, into = c("Treatment", "Time"), regex = "([A-Z]+)([0-9]+)")
#    Treatment Time
# 1          A    1
# 2          A    1
# 3          A    1
# 4          A    1
# 5          A    2
# ::::: snip :::: #
# 11         B    1
# 12         B    1

#3


5  

You can use substr to split it:

您可以使用substr来拆分它:

e.g.

例如

df <- data.frame(treatment =   substr(variable, start = 1, stop = 1),
                 time =        substr(variable, start = 2, stop = 2) )

#4


5  

If you create a data frame with the vector, variable, you could use separate() from the tidyr package now.

如果使用vector,variable创建数据框,则可以立即使用tidyr包中的separate()。

mydf <- data.frame(variable = c(rep("A1", 4), rep("A2", 4), rep("B1", 4)),
                   stringsAsFactors = FALSE)

separate(mydf, variable, c("treatement", "time"), sep = 1)

#   treatement time
#1           A    1
#2           A    1
#3           A    1
#4           A    1
#5           A    2
#6           A    2
#7           A    2
#8           A    2
#9           B    1
#10          B    1
#11          B    1
#12          B    1

#5


4  

Another solution using regular expression

另一种使用正则表达式

require(stringr)
variable <- c(paste0("A", c(rep(1, 4), rep(2, 3))),
              paste0("B", rep(1, 4))
              )

data.frame(
    treatment = str_extract(variable, "[[:alpha:]]"),
    time = as.numeric(str_extract(variable, "[[:digit:]]"))
    )

##    treatment time
## 1          A    1
## 2          A    1
## 3          A    1
## 4          A    1
## 5          A    2
## 6          A    2
## 7          A    2
## 8          B    1
## 9          B    1
## 10         B    1
## 11         B    1

#6


4  

A new function tstrsplit() was introduced in data.table v1.9.5. The t stands for transpose. It's the result of splitting a character vector with strsplit() and then transposing it.

在data.table v1.9.5中引入了一个新函数tstrsplit()。 t代表转置。这是用strsplit()分割字符向量然后转置它的结果。

# dummy data
library(data.table)
dt <- data.table(var = c(rep("A1", 4), rep("A2", 4), rep("B1", 4)))

Using tstrsplit():

使用tstrsplit():

dt[, tstrsplit(var, "")]

    V1 V2
 1:  A  1
 2:  A  1
 3:  A  1
 4:  A  1
 5:  A  2
 6:  A  2
 7:  A  2
 8:  A  2
 9:  B  1
10:  B  1
11:  B  1
12:  B  1

Yes, it's that easy. :-)

是的,就这么简单。 :-)

#7


3  

You can use substring() to create vectors then join them using the data.frame function.

您可以使用substring()创建向量,然后使用data.frame函数将它们连接起来。

yyy<-c("A1", "A1", "A1", "A1", "A2", "A2", "A2", "A2", "B1", "B1", "B1", "B1")

treatment<-substring(yyy, 1,1)

time<-as.numeric(substring(yyy,2,2))

data.frame(treatment,time)

#8


2  

You could just use strsplit

你可以使用strsplit

df <- t(data.frame(strsplit(variable, "")))
rownames(df) <- NULL
colnames(df) <- c("treatment" , "time" )
df
      treatment time
 [1,] "A"       "1" 
 [2,] "A"       "1" 
 [3,] "A"       "1" 
 [4,] "A"       "1" 
 [5,] "A"       "2" 
 [6,] "A"       "2" 
 [7,] "A"       "2" 
 [8,] "A"       "2" 
 [9,] "B"       "1" 
[10,] "B"       "1" 
[11,] "B"       "1" 
[12,] "B"       "1" 

Instead of using t you can use rbind and then coerce to data.frame as follows:

您可以使用rbind而不是使用t,然后强制使用data.frame,如下所示:

setNames(as.data.frame(do.call(rbind, strsplit(variable, ""))), 
         c("Treatment", "Time"))
#    Treatment Time
# 1          A    1
# 2          A    1
# 3          A    1
# 4          A    1
# 5          A    2
# 6          A    2
# 7          A    2
# 8          B    1
# 9          B    1
# 10         B    1
# 11         B    1

#9


1  

Based on the comment of @Justin I suggest this (using v <- c("A1", "B2")):

基于@Justin的评论我建议这个(使用v <- c(“A1”,“B2”)):

> t(sapply(strsplit(v, ''), '[', c(1, 2)))
     [,1] [,2]
[1,] "A"  "1" 
[2,] "B"  "2" 

The vector after `'[' selects the items from the split vector. So I split only once, keeping both items. Maybe this is even easier if you want to keep every item:

''['选择分裂向量中的项后的向量。所以我只拆分一次,保留两个项目。如果你想保留每件物品,这可能更容易:

t(sapply(strsplit(v, ''), identity))

推荐阅读
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • 生成式对抗网络模型综述摘要生成式对抗网络模型(GAN)是基于深度学习的一种强大的生成模型,可以应用于计算机视觉、自然语言处理、半监督学习等重要领域。生成式对抗网络 ... [详细]
  • Android Studio Bumblebee | 2021.1.1(大黄蜂版本使用介绍)
    本文介绍了Android Studio Bumblebee | 2021.1.1(大黄蜂版本)的使用方法和相关知识,包括Gradle的介绍、设备管理器的配置、无线调试、新版本问题等内容。同时还提供了更新版本的下载地址和启动页面截图。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • IjustinheritedsomewebpageswhichusesMooTools.IneverusedMooTools.NowIneedtoaddsomef ... [详细]
  • Android日历提醒软件开源项目分享及使用教程
    本文介绍了一款名为Android日历提醒软件的开源项目,作者分享了该项目的代码和使用教程,并提供了GitHub项目地址。文章详细介绍了该软件的主界面风格、日程信息的分类查看功能,以及添加日程提醒和查看详情的界面。同时,作者还提醒了读者在使用过程中可能遇到的Android6.0权限问题,并提供了解决方法。 ... [详细]
  • Ihaveaworkfolderdirectory.我有一个工作文件夹目录。holderDir.glob(*)>holder[ProjectOne, ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • sklearn数据集库中的常用数据集类型介绍
    本文介绍了sklearn数据集库中常用的数据集类型,包括玩具数据集和样本生成器。其中详细介绍了波士顿房价数据集,包含了波士顿506处房屋的13种不同特征以及房屋价格,适用于回归任务。 ... [详细]
  • C++字符字符串处理及字符集编码方案
    本文介绍了C++中字符字符串处理的问题,并详细解释了字符集编码方案,包括UNICODE、Windows apps采用的UTF-16编码、ASCII、SBCS和DBCS编码方案。同时说明了ANSI C标准和Windows中的字符/字符串数据类型实现。文章还提到了在编译时需要定义UNICODE宏以支持unicode编码,否则将使用windows code page编译。最后,给出了相关的头文件和数据类型定义。 ... [详细]
  • 本文介绍了如何使用Express App提供静态文件,同时提到了一些不需要使用的文件,如package.json和/.ssh/known_hosts,并解释了为什么app.get('*')无法捕获所有请求以及为什么app.use(express.static(__dirname))可能会提供不需要的文件。 ... [详细]
  • 本文整理了315道Python基础题目及答案,帮助读者检验学习成果。文章介绍了学习Python的途径、Python与其他编程语言的对比、解释型和编译型编程语言的简述、Python解释器的种类和特点、位和字节的关系、以及至少5个PEP8规范。对于想要检验自己学习成果的读者,这些题目将是一个不错的选择。请注意,答案在视频中,本文不提供答案。 ... [详细]
  • node.jsrequire和ES6导入导出的区别原 ... [详细]
author-avatar
李小白无悔
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有