[英]Why there is no output when I do R Pattern Matching with For loop
這是我第一次編寫R函數。 我想要做的是例如我有一個R data.frame
這樣
Vars match
1 A_m 0
2 B_m 0
3 C 0
4 D 34
5 E_m 0
這是我匹配兩個數據幀后得到的結果。 在match
列中,如果數字為0,則表示Vars
列中的值不匹配。 例如,在第一行中,A_m在匹配列中為0。 這意味着A_m沒有匹配項。 所以我的功能是在Vars列中找到不匹配的值(在match列中為0)。 之后,如果我找到的值以“ _m”結尾,那么它就是我想要的值,我想將它們打印出來。
這是我寫的代碼。 因為我以前從未編寫過R函數,所以我的代碼可能存在很多問題。 我想使用data.frame
作為函數的參數,並使用for
循環檢查整個dataframe。 在for循環中,我想使用if來決定是否為目標值。 非常感謝您的幫助和耐心。
varsConvert <- function(x){
for(i in 1:nrow(x)){
#x[i,1]is the cordinate of the value in that dataframe, can I write like this?
if(x[i,1] == 0){
#I want to match ends with _m by *_m
if(x[i,0] == "*_m"){
print(x[i,0])
}
else if(x[i,0] == "E"){
print(x[i,0])
}
else{
stop("this is an error")
}
}
}
}
在我的示例中,我要打印的值應為A_m,B_m和E_m
雖然可以在R中for
循環編寫“經典”,但通常最好使用其他功能,這些功能會更短/更干凈/更快。 這是您的數據(我將其命名為df
):
df<-structure(list(Vars = c("A_m", "B_m", "C", "D", "E_m"), match = c(0L,
0L, 0L, 34L, 0L)), .Names = c("Vars", "match"), class = "data.frame", row.names = c(NA,
-5L))
你可以做 :
temp<-df$Vars[df$match==0] # find the names of Vars for which match is equal to 0
temp[grep('_m',temp)] # only select those with _m
# [1] "A_m" "B_m" "E_m"
另一種選擇是在Vars中選擇match == 0和_m的交點的索引:
df$Vars[intersect(grep('_m',df$Vars),which(df$match==0))]
# [1] "A_m" "B_m" "E_m"
還有另一種方法(使用布爾算術而不是集合操作):
df$Vars[ grepl('_m',df$Vars) & df$match==0 ]
如果要在輸入中包含data.frame
的函數,則可以執行此操作(我這次使用列號來顯示其他可能性):
f<-function(data){
temp<-data[,1][data[,2]==0]
temp[grep('_m',temp)]
}
要使用它,請調用f(nameOfYourData)
:
f(df)
# [1] "A_m" "B_m" "E_m"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.