根据具体值创建新的变量 [英] Create new variables based upon specific values

查看:139
本文介绍了根据具体值创建新的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了正则表达式和Hadley Wickham的 stringr dplyr 包,但无法弄清楚如何让这个工作。

I read up on regular expressions and Hadley Wickham's stringr and dplyr packages but can't figure out how to get this to work.

我在数据框中有图书馆流通数据,电话号码是一个字符变量。我想拿起初始大写字母,并将一个新变量和字母和期间之间的数字变成第二个新变量。

I have library circulation data in a data frame, with the call number as a character variable. I'd like to take the initial capital letters and make that a new variable and the digits between the letters and period into a second new variable.

Call_Num
HV5822.H4 C47 Circulating Collection, 3rd Floor
QE511.4 .G53 1982 Circulating Collection, 3rd Floor
TL515 .M63 Circulating Collection, 3rd Floor
D753 .F4 Circulating Collection, 3rd Floor
DB89.F7 D4 Circulating Collection, 3rd Floor 


推荐答案

使用 stringi 包,这将是一个选项。由于您的目标停留在字符串的开头,所以 stri_extract_first()将会运行得很好。 [:alpha:] {1,} 表示包含多个字母的字母序列。使用 stri_extract_first()可以识别第一个字母顺序。同样,您可以使用 stri_extract_first(x,regex =\\ d {1,})找到第一个数字序列。

Using the stringi package, this would be one option. Since your target stays at the beginning of the strings, stri_extract_first() would work pretty well. [:alpha:]{1,} indicates alphabet sequences which contain more than one alphabet. With stri_extract_first(), you can identify the first alphabet sequence. Likewise, you can find the first sequence of numbers with stri_extract_first(x, regex = "\\d{1,}").

x <- c("HV5822.H4 C47 Circulating Collection, 3rd Floor",
       "QE511.4 .G53 1982 Circulating Collection, 3rd Floor",
       "TL515 .M63 Circulating Collection, 3rd Floor",
       "D753 .F4 Circulating Collection, 3rd Floor",
       "DB89.F7 D4 Circulating Collection, 3rd Floor")

library(stringi)

data.frame(alpha = stri_extract_first(x, regex = "[:alpha:]{1,}"), 
           number = stri_extract_first(x, regex = "\\d{1,}"))

#  alpha number
#1    HV   5822
#2    QE    511
#3    TL    515
#4     D    753
#5    DB     89

这篇关于根据具体值创建新的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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