如何在R中的数据帧的某些列中将0转换为NaN? [英] How to convert 0s to NaNs in certain columns of dataframe in R?
本文介绍了如何在R中的数据帧的某些列中将0转换为NaN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
R初学者在这里.
我想在9列中的这6列中将0转换为NaN:"int_t","ext_t","int_h",ext_h," db和" pa.谢谢.
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.
推荐答案
尝试
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"))))
这篇关于如何在R中的数据帧的某些列中将0转换为NaN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文