[英]How do I convert all nonumeric values to NAs in R in a dataframe?
I have a dataframe called returns. 我有一个名为return的数据框。 How do I make the code below more concise?
如何使以下代码更简洁? I tried using apply, lappply and sapply, but they seem to change the structure of the dataframe such that I cannot produce a correlation matrix.
我尝试使用apply,lappply和sapply,但是它们似乎改变了数据框的结构,因此我无法生成相关矩阵。 To clarify: the code below works, but I would like to make it more concise.
需要澄清的是:下面的代码有效,但是我想使其更加简洁。 Thanks!
谢谢!
returns$VIT <- as.numeric(as.character(returns$VIT))
returns$EFA <- as.numeric(as.character(returns$EFA))
returns$VWO <- as.numeric(as.character(returns$VWO))
returns$VIG <- as.numeric(as.character(returns$VIG))
returns$VNQ <- as.numeric(as.character(returns$VNQ))
returns$iPath.DJP <- as.numeric(as.character(returns$iPath.DJP))
returns$iShares.MUB <- as.numeric(as.character(returns$iShares.MUB))
cor(returns, use="pairwise.complete.obs")
EDIT: The following test code does NOT work, I am trying to figure out how to make it work. 编辑:以下测试代码不起作用,我试图弄清楚如何使其工作。
test <- data.frame(c(.04,.2,"blah"),c(.01,.24,"blah"))
colnames(test) <- c("VIT", "EFA")
new <- apply(test, 2, function(x) as.numeric(as.character(x)))
cor(test, use="pairwise.complete.obs")
test <- data.frame(a = rep("bob", 12), b = rep(c(1,23,4), times = 4))
Filter(is.numeric, test)
Returns only the numeric columns in test
. 仅返回
test
的数字列。 You can use lapply(test, is.numeric)
to get the true/false results yourself and do something with that. 您可以使用
lapply(test, is.numeric)
自己获取对/错结果,并对此进行处理。
Is this what you're looking for? 这是您要找的东西吗?
numeric.columns <- c('VIT','EFA','VWO','VIG','VNQ','iPath.DJP','iPath.DJP','iShares.MUB')
returns[,numeric.columns] <- lapply(returns[,numeric.columns], function(x) as.numeric(as.character(x)))
cor(returns, use="pairwise.complete.obs")
Just use plyr
's colwise
. 只需使用
plyr
的colwise
。
returns = colwise(function(x) as.numeric(ifelse(is.numeric(x),x,NA)))(returns)
It takes a function and applies it to all columns. 它接受一个函数并将其应用于所有列。 The final result should be numeric.
最终结果应该是数字。 Note that this treats values such as
'1'
as NA. 请注意,这会将
'1'
值视为NA。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.