r - Why is R having such a hard time converting a text file full of numbers into numbers?
问题描述
The following short snipped of code:
> # Clear the console in RStudio
> cat("\014")
>
>
> setwd("C:/Users/name/Desktop/Project1v3/Fit_Index_Data/")
> dataVectorTemp <- read.table("CFI1.txt", header = FALSE)
> dataVector <- as.numeric(dataVectorTemp)
> mean(dataVector)
results in the following error message:
Perhaps it is because it's late at night as I write this, but I feel assaulted as to how a language like R can do such a good job of doing the wrong thing when it comes to something as simple as reading a *.txt
file full of number in and finding the average.
I'm aware that R has to somehow convert these numbers from chars
and string
(from the original file) to floats (or as.numeric
), but be darned if I know how to phrase my question other than to say that I am rather lost and defeated.
I'm not sure why I'm so boggled by this, but it has been as if R is playing a practical joke on me.
解决方案
您可以尝试将 all 转换为数字(NA
如果不是数字),然后na.rm = TRUE
在mean
函数内使用。
dataVector <- sapply(dataVectorTemp, function(x) as.numeric(x))
mean(dataVector, na.rm = TRUE)
推荐阅读
- mips - MARS 上的 Mips 汇编语言
- python - 在 Pyspark 中读取和保存图像文件
- sql - PostgreSQL - 如何在条件后连接行值
- java - 为什么 ISO 8583 解包会产生无效值?
- ios - 带有 CFNotificationCenter 强引用的 UIViewController 不会发布
- html - 隐藏链接,除非在小屏幕上
- javascript - xhttp.open 函数没有响应
- css - 垂直对齐顶部不适用于 dt 和 dd 元素
- list - 如何在 Java 中循环赋予队列列表各种名称?
- mysql - MySQL (Aurora) 使用 adddate 或 date-add 或 date-sub 更新时间戳表示语法错误