-1
我有兩個數據幀,df1和df2。檢查數值是否爲R
DF1:
col1 <- c('30','30','30','30')
col2 <- c(3,13,18,41)
col3 <- c("heavy","light","blue","black")
df1 <- data.frame(col1,col2,col3)
>df1
col1 col2 col3
1 30 3 heavy
2 30 13 light
3 30 18 blue
4 30 41 black
DF2:
col1 <- c('10',"NONE")
col2 <- c(21,"NONE")
col3 <- c("blue","NONE")
df2 <- data.frame(col1,col2,col3)
>df2
col1 col2 col3
1 10 21 blue
2 NONE NONE NONE
我寫了一點腳本來表達;如果col3中的值等於「light」,我想刪除該行以及數據幀中的所有後續行。所以DF1會是什麼樣子:
col1 col2 col3
1 30 3 heavy
而且不會有什麼變化DF2(因爲它沒有火柴COL3以「光」)。
我已經說過上面有兩個單獨的df作爲兩個例子,但下面的腳本只是提到了一個通用的「df」來保存我複製並粘貼同一位代碼的兩次df1與df2一起復制。
phrase=c("light")
start_rownum=which(grepl(phrase, df[,3]))
end_rownum=nrow(df)
end_rownum=as.numeric(end_rownum)
if(start_rownum > 0){
df=df[-c(start_rownum:end_rownum),]
}
由於start_rownum有一個數值,所以此腳本可以與df1一起使用。但是,我得到DF2以下錯誤:
Error in start_rownum:end_rownum : argument of length 0
不要說:「如果(start_rownum> 0)」,是有一些方法來檢查,如果有start_rownum數值?我找不到工作解決方案。
謝謝。
取代' 「NONE」'使用'NA',例如,'C(10,NA )'。如果這是您導入的數據,請在導入期間設置'na.string'參數。然後該列將爲數字,R提供許多用於處理「NA」值的工具,例如'na.omit'或'is.na'。 – Roland