Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

r - Adding row to a data frame with missing values

So I have this data frame

df <- data.frame( A=1:10, B=LETTERS[1:10], C=letters[1:10], stringsAsFactors= F )

I want to add a row to this data frame with A=11 and C="K", but I don't have the information on the column C. In fact, I have no idea a priori what other columns are there in the data frame, except for A and B. These missing columns should get an NA. The best I could come up is this:

tmp <- rep( NA, ncol( df ) ) # Batman!
df <- rbind( df, tmp )
df[ nrow( df ), "A" ] <- 11
df[ nrow( df ), "B" ] <- "K"

Is there a simpler way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Base version:

new.row <- list(A=11, B="K")
df[nrow(df) + 1, names(new.row)] <- new.row

plyr version:

library(plyr)
new.row <- data.frame(A=11, B="K", stringsAsFactors=F)
df <- rbind.fill(df, new.row)

Both produce:

    A B    C
1   1 A    a
2   2 B    b
3   3 C    c
4   4 D    d
5   5 E    e
6   6 F    f
7   7 G    g
8   8 H    h
9   9 I    i
10 10 J    j
11 11 K <NA>

You can also generalize the base version to more rows:

more.rows <- data.frame(A=15:20, B=letters[15:20], stringsAsFactors=F)
df[(nrow(df) + 1):(nrow(df) + nrow(more.rows)), names(more.rows)] <- more.rows

producing:

    A B    C
1   1 A    a
2   2 B    b
3   3 C    c
4   4 D    d
5   5 E    e
6   6 F    f
7   7 G    g
8   8 H    h
9   9 I    i
10 10 J    j
11 11 K <NA>
12 15 o <NA>
13 16 p <NA>
14 17 q <NA>
15 18 r <NA>
16 19 s <NA>
17 20 t <NA>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...