首页 > 解决方案 > 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:

enter image description here

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.

标签: r

解决方案


您可以尝试将 all 转换为数字(NA如果不是数字),然后na.rm = TRUEmean函数内使用。

dataVector <- sapply(dataVectorTemp, function(x) as.numeric(x))

mean(dataVector, na.rm = TRUE)


推荐阅读