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
947 views
in Technique[技术] by (71.8m points)

dataframe - R: Adding NAs into Data Frame

I have a data frame like so:

Name   Position   Value
a         1        0.2
a         3        0.4
a         4        0.3
b         1        0.5
b         2        0.4
b         5        0.3
c         2        0.3
c         3        0.4
c         5        0.1
d         1        0.2
d         2        0.4
d         3        0.5

I want to make it so that Position always go from 1 to 5 for each Name and fill in NAs into Value like so:

Name   Position   Value
a         1        0.2
a         2        NA
a         3        0.4
a         4        0.3
a         5        NA
b         1        0.5
b         2        0.4
b         3        NA
b         4        NA
b         5        0.3
c         1        NA
c         2        0.3
c         3        0.4
c         4        NA
c         5        0.1
d         1        0.2
d         2        0.4
d         3        0.5
d         4        NA
d         5        NA

Is there a way to do it without creating a dummy data frame with the first 2 columns then doing some sort of outer join with merge?

Thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I would use data.table but in a different way that @akrun underlined:

library(data.table)
dt = as.data.table(df)
setkey(dt, Name, Position)
dt[CJ(unique(Name),unique(Position))]

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

...