简体   繁体   English

在R中,如何使用正则表达式处理数据框中的变量?

[英]In R, how can I manipulate variable in dataframe using regular expression?

This is the dataset 这是数据集

df1 <- data.frame("id" = c("ebi.ac.uk:MIAMExpress:Reporter:A-MEXP-503.100044", 
                       "ebi.ac.uk:MIAMExpress:Reporter:A-MEXP-783.100435",
                       "ebi.ac.uk:MIAMExpress:Reporter:C-DEA-783.100435"),
              "Name" = c("ABC", "DEF", ""))

The product of the dataset 数据集的乘积

                                                  id   Name
1   ebi.ac.uk:MIAMExpress:Reporter:A-MEXP-503.100044    ABC
2   ebi.ac.uk:MIAMExpress:Reporter:A-MEXP-503.100435    DEF
3   ebi.ac.uk:MIAMExpress:Reporter:A-MEXP-503.100488     

I want to make the dataframe look like this 我想使数据框看起来像这样

       id     Name
1  100044      ABC
2  100435      DEF
3  100488       NA 

Can anyone show me how to approach this problem? 谁能告诉我如何解决这个问题?

Regex way to find the last dot: 正则表达式查找最后一个点的方法:

df1$id <- as.character(df1$id)
regexpr("\\.[^\\.]*$", df1$id) # may not need \\ on second one

or sapply(gregexpr("\\\\.", x), tail, 1) sapply(gregexpr("\\\\.", x), tail, 1)

Easier to remember, non-regex way: 较容易记住的非正则表达式方式:

df1$id <- as.character(df1$id)

df1$id <- sapply(strsplit(df1$id,split="\\."),tail,1)
df1$Name[df1$Name == ""] <- NA

df1
  id Name 1 100044 ABC 2 100435 DEF 3 100435 <NA> 

sapply(strsplit(df1$id,split="\\\\."),tail,1) is from here . sapply(strsplit(df1$id,split="\\\\."),tail,1)这里开始

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM