簡體   English   中英

如何在R的數據幀的某些列中將0轉換為NaN?

[英]How to convert 0s to NaNs in certain columns of dataframe in R?

R初學者在這里。
我想在9列中的這6列中將0s轉換為NaN:“ int_t”,“ ext_t”,“ int_h”,ext_h”,“ db”和“ pa”。

有一個is.na.data.frame函數,但沒有is.na<-.data.frame ,所以...僅可能:

is.na( dfrm[ , c( "int_t", "ext_t", "int_h", ext_h", "db", "pa")] ) <- 
     dfrm[ , c( "int_t", "ext_t", "int_h", ext_h", "db", "pa")]==0

您應該提供一個測試用例。 (但是,既然我已經對其進行了測試,我認為ti應該會成功。)

嘗試

nm <- c("int_t", "ext_t", "int_h", "ext_h", "db", "pa")
df[nm] <- (NaN^!df[nm])*df[nm]
df
#   int_t ext_t int_h ext_h ColN  db pa
#1      5     2     5     4    2   2  4   
#2      5     4   NaN     4    2   2  5
#3      1     5     5     2    0   2  4
#4      4     1     5     4    5   4  3
#5      3     2   NaN   NaN    2 NaN  5
#6      3     5     3     4    5   4  1
#7      4     5     2   NaN    5   4  1
#8    NaN   NaN     5     1    3   1  4
#9      3     2     2     5    5   1  4
#10     4     3     5     3    3   3  1

數據

set.seed(42)
df <- as.data.frame(matrix(sample(0:5, 7*10, replace=TRUE), 
    ncol=7, dimnames=list(NULL, c( "int_t", "ext_t", "int_h", 
   "ext_h", "ColN", "db", "pa"))))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM