簡體   English   中英

從 TXT 文件中提取邏輯條件並將其應用於 R 中的數據

[英]Extract the logical conditions from TXT file and apply them to a data in R

我正在嘗試使用 R 來提取在 txt 文件中找到的一些操作條件(即 X>10)並將它們應用於 R 中的附加數據。 因此,我將數據附加到 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"                  ""         

請參閱 txt 每個模式都有條件。 我需要自動提取這些條件作為邏輯條件。 換句話說,如果我有X4=120滿足第一個條件,假設一個新變量p=0而不滿足第二個條件,所以p=1

如何在 R 中執行此操作?

您可以使用evalstr2lang來成功。

x<-5
str_cond<-"x<3"
condition<-str2lang(str_cond)
eval(condition) #prints FALSE

對於您的示例,將您的字符串條件拆分為左右部分,並將左側部分用作 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM