我有一個數據幀有多個變量,其中有一個字符串(變量),我試圖確定an
變量中的字符串是否出現在string
列中。每個an
變量都有相應的變量cn
。例如,如果a1
中的字符串出現在string
中,我希望c1
中包含Checked
,依此類推。我爲此開發了下面的for循環解決方案(本文後面的一些示例數據),但我想知道是否有適用於此的解決方案,可能會更快,更容易編寫代碼?在真實數據中,有超過100個a和c變量。將多個for循環應用於家庭解決方案?
#For loop solution
for (var in seq(2, 10, 2)){
for (i in 1:nrow(df)){
df[i, var]<-ifelse(grepl(df[i, var-1], df$string[i])=="TRUE", "Checked", "Unchecked")
}
}
#### Example data ####
a1<-c("zebra", "giraffe", "elephant")
a2<-c("hyena", "monkey", "antelope")
a3<-c("badger", "deer", "kangaroo")
a4<-c("tiger", "lion", "coyote")
a5<-c("penguin", "bear", "gorilla")
c1<-""
c2<-""
c3<-""
c4<-""
c5<-""
string<-c("elephant/bear/coyote/penguin/monkey",
"giraffe/antelope/monkey/gorilla/tiger",
"elephant/antelope/kangaroo/coyote/gorilla")
df<-cbind.data.frame(a1, c1, a2, c2, a3, c3, a4, c4, a5, c5, string,
stringsAsFactors=F)