String 将字符串转换为数字
我已经导入了一个测试文件,并试图制作一个直方图String 将字符串转换为数字,string,r,String,R,我已经导入了一个测试文件,并试图制作一个直方图 pichman <- read.csv(file="picman.txt", header=TRUE, sep="/t") hist <- as.numeric(pichman$WS) pichman我怀疑你在因素方面有问题。比如说, > 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 &
pichman <- read.csv(file="picman.txt", header=TRUE, sep="/t")
hist <- as.numeric(pichman$WS)
pichman我怀疑你在因素方面有问题。比如说,
> 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”。您期望/希望
作为.numeric
对这些值做什么
- 在
read.csv
中,尝试使用参数stringsAsFactors=FALSE
- 您确定它是
sep=“/t
而不是sep=“\t”
- 使用命令
head(pitchman)
检查数据的前几行
- 另外,当您不提供数据时,猜测您的问题是什么是非常棘手的。最好使用最小的工作示例。例如,我无法运行csgillespie所说的命令
pichman。stringsAsFactors默认为TRUE,它将任何文本转换为一个因子。因此,即使删除文本,您的d中仍然有一个因子ataframe
现在,关于转换,有一种更为优化的方法。因此,我将其放在这里作为参考:
> x <- factor(sample(4:8,10,replace=T))
> x
[1] 6 4 8 6 7 6 8 5 8 4
Levels: 4 5 6 7 8
> as.numeric(levels(x))[x]
[1] 6 4 8 6 7 6 8 5 8 4
>x
[1] 6 4 8 6 7 6 8 5 8 4
级别:45 6 7 8
>as.数字(级别(x))[x]
[1] 6 4 8 6 7 6 8 5 8 4
证明它是有效的
时间安排:
> x <- factor(sample(4:8,500000,replace=T))
> system.time(as.numeric(as.character(x)))
user system elapsed
0.11 0.00 0.11
> system.time(as.numeric(levels(x))[x])
user system elapsed
0 0 0
>x系统时间(作为数字(作为字符(x)))
用户系统运行时间
0.11 0.00 0.11
>系统时间(作为数字(级别(x))[x])
用户系统运行时间
0 0 0
这是一个很大的改进,但并不总是一个瓶颈。但是,如果您有一个大数据帧和许多列要转换,这一点就变得非常重要。我在一个新的答案中添加了一个时间点。+1为您提供了正确的时间点,并提供了所有选项。非常感谢!我删除了值“Down”和“NoData”“在我看到不仅仅是数字之后,是的,我的斜线被混合到了优秀+1。这确实帮助了我。请参阅,在导入csv文件后,您可以使用hablar::retype
,它会将所有列转换为适当的数据类型,即从不考虑因素。所以只需添加pichman%>%retype
。
> x <- factor(sample(4:8,500000,replace=T))
> system.time(as.numeric(as.character(x)))
user system elapsed
0.11 0.00 0.11
> system.time(as.numeric(levels(x))[x])
user system elapsed
0 0 0