R用NA替换textConnection中缺少的元素

时间:2013-05-29 03:25:11

标签: r

如果我这样做

a = read.table(textConnection('a b c d
1 2 3 4
a b c
1 2 3 4','r'),header=T)

我收到错误

Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  : 
  line 3 did not have 4 elements

如何让R用NA替换丢失的元素而不是出错?

1 个答案:

答案 0 :(得分:4)

使用fill=TRUE

a = read.table(textConnection('a b c d
1 2 3 4
a b c
1 2 3 4','r'),header=T, fill=TRUE)

a
##   a b c  d
## 1 1 2 3  4
## 2 a b c NA
## 3 1 2 3  4