[英]Extract the logical conditions from TXT file and apply them to a data in R
I am trying to use R to extract some operational condition (ie X>10) found in txt file and apply them to attached data in R.我正在尝试使用 R 来提取在 txt 文件中找到的一些操作条件(即 X>10)并将它们应用于 R 中的附加数据。 So, I attached a data to R in csv format of row=40 and column=4 (X1,X2,X3,X4).
因此,我将数据附加到 R 中,格式为 csv,行 = 40,列 = 4(X1,X2,X3,X4)。
dat1=readLines("Patterns Interpreted.txt")
dat1
[1] "-------------------------" " Class 1 Vs. Class 0" "-------------------------"
[4] "Pattern 1" "X4 Less Than 141.5" ""
[7] "-------------------------" " Class 0 Vs. Class 1" "-------------------------"
[10] "Pattern 1" "X4 Greater Than 141.5" ""
dat2<-read.csv("LR.csv")
dat2
X1 X2 X3 X4 X5 X6 Y
1 2140 20640 30250 205 1732 99 4540
2 2016 20280 30010 195 1697 100 4315
3 1905 19860 29780 184 1662 97 4095
# For replacement in txt file
tx2 <- gsub(pattern = " Less Than ", replace = "<", x = dat1)
tx22 <- gsub(pattern = " Greater Than ", replace = ">", x = tx2)
tx22
[1] "-------------------------" " Class 1 Vs. Class 0" "-------------------------"
[4] "Pattern 1" "X4<141.5" ""
[7] "-------------------------" " Class 0 Vs. Class 1" "-------------------------"
[10] "Pattern 1" "X4>141.5" ""
Refer to txt there is condition for each pattern.请参阅 txt 每个模式都有条件。 I need to extract these conditions automatically as logical conditions.
我需要自动提取这些条件作为逻辑条件。 In other words, if I have
X4=120
which satisfy the first condition let say a new variable p=0
while does not satisfy the second condition so p=1
.换句话说,如果我有
X4=120
满足第一个条件,假设一个新变量p=0
而不满足第二个条件,所以p=1
。
How to do this in R?如何在 R 中执行此操作?
You can use eval
with str2lang
to succeed that.您可以使用
eval
和str2lang
来成功。
x<-5
str_cond<-"x<3"
condition<-str2lang(str_cond)
eval(condition) #prints FALSE
For your example split your string condition to right and left part and use the left part as string index name to your dat1 to get the column you want.对于您的示例,将您的字符串条件拆分为左右部分,并将左侧部分用作 dat1 的字符串索引名称以获取您想要的列。
str_cond<-"X4<141.5"
cond_parts<-strplit(str_cond,"<")[[1]] # split string
assign(cond_parts[1],dat1[,cond_parts[1]]) # create variable with name the left part and assign the column
condition<-str2lang(str_cond) # create language condition
eval(condition) # execute the language condition
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.