以下是檢查特定條件(如果連續兩行具有相同值)後在數據框中插入新列的簡單循環。 代碼工作得很好,但我想提高我的編碼技能,所以我要求其他解決方案(更快,更優雅)。 我檢查了以前的話題,並瞭解了很多,但我對我的具體案例很好奇。 感謝您的任何輸入。改進我的編碼「for循環」
vector<-1
vector_tot<-NULL
for(i in 1:length(dat$Label1))
{
vector_tot<-c(vector_tot,vector)
if(dat$Label1[i]==dat$Label1[i+1]){
vector<-0
}
else {
vector<-1
}
}
dat$vector<- vector_tot
猜測'NA'應該在底部而非頂部(循環開始於1,它的下一個元素搜索,而不是以前的)。 – nicola
'dat $ Label1 == c(tail(dat $ Label1,-1),NA)'作爲同一方法的不同概念 – thelatemail
謝謝尼科拉,調整了答案。 – Florian