[英]If string meets a pattern then edit R
I have a large list of data. 我有大量的数据。 I want to edit it according to some pattern recognition.
我想根据某种模式识别对其进行编辑。 For example:
例如:
if I have a letter then I want to print that letter and some additional characters after. 如果我有一个字母,那么我想在那之后打印该字母和一些其他字符。
If I have some numbers I want to print the numbers and some additional characters after. 如果我有一些数字,我想在其后打印数字和一些其他字符。
If I have a unique character like "@" "#" "/" and/or ":" Then I want to subsitute it with a space. 如果我有一个独特的字符,例如“ @”,“#”,“ /”和/或“:”,那么我想用一个空格代替它。
If I have n (n being a number like 9) numbers then n (n being a number) characters then I want to print what I have and add some letters or characters to the end of the string. 如果我有n个(n是一个像9的数字),然后有n个(n是一个数字)字符,那么我想打印我所拥有的字符,并在字符串的末尾添加一些字母或字符。
So let a data set be
data output
F F State
M M State
R R State
55 55 Object
53 53 Object
993M@L 99M L Object
93283M 93283M State0
I think it would be similar to a ifelse(if there are 5 numbers followed 1 letter, original space State0,NA) 我认为这类似于ifelse(如果5个数字后跟1个字母,则原始状态为State0,NA)
I would also like the NA,so that way I can see in my data what does not match the rules that I make. 我还希望使用NA,这样我就可以在数据中看到与我制定的规则不匹配的内容。
This is my first time working on this and I am researching but most of the resources are not for R. Any additional help is great! 这是我的第一次研究,我正在研究,但是大多数资源都不适合R。任何其他帮助都很棒!
You can use the following function with grepl
and gsub
: 您可以对
grepl
和gsub
使用以下功能:
test<-function(str){
if(grepl("^[A-Z]$", str, perl=TRUE)){
gsub("^([A-Z])$", "\\1 State", str)
}
else if(grepl("^\\d+$", str, perl=TRUE)){
gsub("^(\\d+)$", "\\1 Object", str)
}
else if(grepl("[@#/:]", str, perl=TRUE)){
str<-gsub("[@#/:]", " ", str)
paste(str," Object")
}
else if(grepl("^\\d+[A-Z]+$", str, perl=TRUE)){
gsub("^(\\d+[A-Z]+)$", "\\1 State0", str)
}
}
x<-"F"
x<-test(x)
print(x) //output: "F State"
x<-"55"
x<-test(x)
print(x) //output: "55 Object"
x<-"993M@L"
x<-test(x)
print(x) //output: "993M L Object"
x<-"93283M"
x<-test(x)
print(x) //output: "93283M State0"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.