我已经使用readr包导入了一个.csv (让我们称之为x),它产生了一个tibble。
编辑:由于readr生成的实际 tibble与下面发布的problems(x)-tibble之间存在混淆,下面是生成问题的实际 tibble的开始部分
> x
# A tibble: 46,080 x 18
x_1 x_2 x_3 x_4 x_5 x_6 x_7 x_8 x_9 x_10 x_11 x_12 x_13 x_14 x_15
<int> <int> <int> <int> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <int>
1 1 1 1 1 29 84.4 72.5 10.1 48.5 35.3 34.2 293. 117. 24.5 20
2 1 1 1 2 120 214. 142. -0.488 55.8 42.1 36.3 589. 124. 257. 84
3 1 1 1 3 28 258. 42.3 2.09 43.7 29.2 32.1 352. 117. 72.2 19
4 1 1 1 4 39 623. 249. 12.1 95.7 75.7 58.6 998. 176. 243. 14
5 1 1 1 5 222 320. 244. -2.10 70.7 51.4 48.4 1232. 242. 711. 111
6 1 1 1 6 33 485. 142. 12.3 61.8 51.9 34.6 764. 117. 160. 24
7 1 1 1 7 32 884. 458. 11.0 110. 88.1 64.5 1525. 237. 283. 5
8 1 1 1 8 58 695. 187. -12.7 64.6 50.5 41.7 1090. 175. 403. 37
9 1 1 2 1 46 58.0 65.3 5.10 49.4 35.2 34.7 234. 117. 26.7 18
10 1 1 2 2 136 217. 191. -0.431 60.5 43.2 42.2 706. 185. 295. 72
# ... with 46,070 more rows, and 3 more variables: x_16 <dbl>, x_17 <dbl>, x_18 <dbl>为了避免错误地读取数据,我尝试了read_csv的read_csv属性的各种组合,但是,我没有让它适合我的情况:在使用readr包时,我收到了一条关于某些列中问题的消息,所以我使用>problems(x)来了解发生了什么。这是输出:
> problems(x)
# A tibble: 264 x 5
row col expected actual file
<int> <chr> <chr> <chr> <chr>
1 1992 x_5 an integer NaN 'raw-data/x.csv'
2 1992 x_15 an integer NaN 'raw-data/x.csv'
3 2320 x_5 an integer NaN 'raw-data/x.csv'
4 2320 x_15 an integer NaN 'raw-data/x.csv'
5 2581 x_5 an integer NaN 'raw-data/x.csv'
6 2581 x_15 an integer NaN 'raw-data/x.csv'
7 2582 x_5 an integer NaN 'raw-data/x.csv'
8 2582 x_15 an integer NaN 'raw-data/x.csv'
9 2583 x_5 an integer NaN 'raw-data/x.csv'
10 2583 x_15 an integer NaN 'raw-data/x.csv'
# ... with 254 more rows我确实理解,显然在几个列和几行中,.csv读取失败了,这导致在需要整数的字段中出现NaN。
我试图通过使用is.nan方法将那些NaN转换为“真实的”NA,但这失败了,因为该方法似乎不支持整个tibbles。
> x[is.nan(x)] <- NA #convert NaN to NA
Error in is.nan(x): default method not implemented for type 'list'我也尝试使用来自naniar包的naniar方法,但是这也失败了。
> replace_with_na_all(data = x, condition = ~.x == NaN)
Error in .x[sel] <- map(.x[sel], .f, ...) : NAs are not allowed in subscripted assignments因此,我正在寻找一种方法来转换、所有、NaN在所有列中以及所有带有NA的行一起转换,或者避免在read_csv期间一起创建NaN。
发布于 2018-07-01 14:37:48
虽然这只是对我自己问题的部分回答(它没有告诉您如何将NaN问题转换为NA问题),但我想指出一个可能的解决方案,以防问题是由同一根源引起的。
我想要与.csv一起导入的readr是由Matlab编写的,并在Matlab中值为NaN的单元格中包含了字符串NaN。因此,识别一个数字的问题不是R,而是NaN作为字符串包含的问题。
在na = "NaN"中使用read_csv属性显然解决了这个问题。
https://stackoverflow.com/questions/51123341
复制相似问题