R beginner here.
I would like to convert 0s into NaNs in these 6 of the 9 columns: "int_t", "ext_t", "int_h", ext_h", "db", and "pa". Thanks.
Asked
Active
Viewed 59 times
-1

Evan
- 217
- 2
- 13
-
2You can try `nm <- c("int_t", "ext_t", "int_h", "ext_h", "db", "pa"); df[nm] <- lapply(df[nm], function(x) { x[x == 0L] <- NaN; x })`. And also please read about [how to create a reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Rich Scriven Nov 21 '14 at 01:12
2 Answers
1
There is an is.na.data.frame
function, but no is.na<-.data.frame
, so ... only perhaps:
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
You should provide a test case. (But now that I have tested it I think ti should succeed.)

IRTFM
- 258,963
- 21
- 364
- 487
1
Try
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
data
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"))))

akrun
- 874,273
- 37
- 540
- 662