本文介绍了将字符串转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我导入了一个测试文件并尝试制作直方图
I've imported a test file and tried to make a histogram
pichman <- read.csv(file="picman.txt", header=TRUE, sep="/t")
hist <- as.numeric(pichman$WS)
但是,我从数据集中的值中得到了不同的数字.本来以为是因为有文字,所以删了文字:
However, I get different numbers from values in my dataset. Originally I thought that this because I had text, so I deleted the text:
table(pichman$WS)
ws <- pichman$WS[pichman$WS!="Down" & pichman$WS!="NoData"]
但是,我的数字仍然很高,有人知道吗?
However, I am still getting very high numbers does anyone have an idea?
推荐答案
我怀疑您对因子有问题.例如,
I suspect you are having a problem with factors. For example,
> x = factor(4:8)
> x
[1] 4 5 6 7 8
Levels: 4 5 6 7 8
> as.numeric(x)
[1] 1 2 3 4 5
> as.numeric(as.character(x))
[1] 4 5 6 7 8
一些评论:
- 您提到您的向量包含字符Down"和NoData".期望/希望
as.numeric
对这些值做什么? - 在
read.csv
中,尝试使用参数stringsAsFactors=FALSE
- 你确定是
sep="/t
而不是sep="\t"
- 使用命令
head(pitchman)
检查数据的前几行 - 此外,当您不提供数据时,很难猜测您的问题是什么.最小的工作示例总是可取的.例如,我不能运行命令
pichman <- read.csv(file="picman.txt", header=TRUE, sep="/t")
因为我没有访问数据集.
- You mention that your vector contains the characters "Down" and "NoData". What do expect/want
as.numeric
to do with these values? - In
read.csv
, try using the argumentstringsAsFactors=FALSE
- Are you sure it's
sep="/t
and notsep="\t"
- Use the command
head(pitchman)
to check the first fews rows of your data - Also, it's very tricky to guess what your problem is when you don't provide data. A minimal working example is always preferable. For example, I can't run the command
pichman <- read.csv(file="picman.txt", header=TRUE, sep="/t")
since I don't have access to the data set.
这篇关于将字符串转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!