測試程式碼如下
data = data.frame("id" = c(1,2,3), "y1" = c("f1","f2","f2"), "x1" = c("pd1","pd2","pd3"))
y1 = unique(data$y1)
a = c()
for(i in 1:length(y1)){
#print(y1[i])
#i = 2
dd = data[data$y1==y1[i],]
str2 = ""
str1 = paste0(y1[i],"=~")
for (k in 1:dim(dd)[1]) {
if(k == dim(dd)[1]){
str2 = paste0(str2,dd$x1[k])
}else{
str2 = paste0(str2,dd$x1[k],"+")
}
}
a[i] = paste0(str1,str2)
}
b = ""
for (i in 1:length(a)) {
b = paste0(b,a[i]," ")
}
print(b)
最終b會呈現 "f1=~pd1 f2=~pd2+pd3 "
但是在建立model時似乎需要將其變成
"f1=~pd1
f2=~pd2+pd3 "
請問是否有方法能夠做到?