我有一个数据帧有多个变量,其中有一个字符串(变量),我试图确定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)