问题描述
假设我有一个 data.frame
完全 numeric
。如果我使第一列的一个条目字符
(例如),那么整个第一列将变为 character
。
Suppose I have a data.frame
that's completely numeric
. If I make one entry of the first column a character
(for example), then the entire first column will become character
.
问题:如何撤消此操作。也就是说,如何使得字符
中的 data.frame
中的任何数字
对象被强制为数字
?
Question: How do I reverse this. That is, how do I make it such that any character
objects inside the data.frame
that are "obviously" numeric
objects are forced to be numeric
?
MWE:
test <- data.frame(matrix(rnorm(50),10))
is(test[3,1])
test[1,1] <- "TEST"
is(test[3,1])
print(test)
所以我的目标是从 test
到 test [2:10]
为数字
的状态。所以我想我要求一个函数,在一个完整的 data.frame
。
So my goal here would be to go FROM the way that test
is now, TO a state of affairs where test[2:10]
is numeric
. So I guess I'm asking for a function that does this over an entire data.frame
.
推荐答案
简短的答案是你不能。
正如评论中提到的,列的所有元素必须具有相同的模式。
Short answer is you cannot.
As was mentioned in the comments, in a data frame, all elements of a column must have the same mode.
如果你想特别找到数字的值,你可以使用下面的代码(其中 vec
If you would like to specifically find the values that are "number like" you can use the following (where vec
here would be, say, a data frame column)
vec[!is.na(as.numeric((vec)))]
然后,您可以转换这些,但不幸的是,您不能将转换的值柱。和你一样,他们将被强制回字符
You can then convert these, but unfortunately you cannot put the converted values back into the same column. As as you do, they will be coerced back to character
对于可以将整个数据帧转换为数字的函数(意识到不可能将特定条目作为异常隔离),可以使用 sapply
As for a function that can convert the whole dataframe to numeric (realizing that isolating specific entries as exceptions is not possible), you can use sapply
sapply(dataFrameName, as.numeric)
这篇关于数据框将整个列从数字类型转换为字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!