我正在讀一個.csv到R中,其中有幾個不同的變量類型,其中兩個以字符形式讀入,儘管它們是數字(十進制度的經度和緯度)。要解決這個問題,我在閱讀它們之後將它們定義爲「as.numeric」。有沒有更好的方法來做到這一點?也許在調用「read.csv」?R,使用read.csv在一個步驟中將數字讀入字符?
d <- read.csv("data.csv",stringsAsFactors=F)
> str(d)
'data.frame': 467674 obs. of 7 variables:
$ station : chr "USC00036506" "USC00036506" "USC00036506" "USC00036506" ...
$ station_name: chr "SEARCY AR US" "SEARCY AR US" "SEARCY AR US" "SEARCY AR US" ...
$ lat : chr "35.25" "35.25" "35.25" "35.25" ...
$ lon : chr "-91.75" "-91.75" "-91.75" "-91.75" ...
$ tmax : int 50 50 39 100 72 61 -17 -44 6 0 ...
$ tmin : int -39 -39 -89 -61 -6 -83 -144 -150 -161 -128 ...
$ tobs : int 33 22 17 61 61 -78 -50 -94 -22 -11 ...
d$lat <- as.numeric(d$lat)
d$lon <- as.numeric(d$lon)
> str(d)
'data.frame': 467674 obs. of 7 variables:
$ station : chr "USC00036506" "USC00036506" "USC00036506" "USC00036506" ...
$ station_name: chr "SEARCY AR US" "SEARCY AR US" "SEARCY AR US" "SEARCY AR US" ...
$ lat : num 35.2 35.2 35.2 35.2 35.2 ...
$ lon : num -91.8 -91.8 -91.8 -91.8 -91.8 ...
$ tmax : int 50 50 39 100 72 61 -17 -44 6 0 ...
$ tmin : int -39 -39 -89 -61 -6 -83 -144 -150 -161 -128 ...
$ tobs : int 33 22 17 61 61 -78 -50 -94 -22 -11 ...
使用'colClasses'參數設置您的列類。 – Andrie
我想你可能在你的長列和拉列中有東西搞亂了函數,阻止它讀取數字值。也許是一個奇怪的NA?在至少一個單元格中逗號爲十進制值? –
是的,@RomanLuštrik,緯度/經度欄中有NAs。 – seapen