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

r - Transfer values from one dataframe to another

I have two data frames. The first looks like this:

value <- seq(1, 100, length.out=20)
df1 <- data.frame(id=as.character(1:20), 
                  value=value, 
                  stringsAsFactors=F)

I have a second dataframe that looks like this

df2 <- data.frame(id=as.character(c(1:5, 21:23)),
                  v2=NA, 
                  stringsAsFactors=F)

I need the values transferring from df1 to df2, but only where df1$id == df2$id. So the dataframe I need is:

df2Needed <- data.frame(id=as.character(c(1:5, 21:23)),
                      v2=c(value[1:5], NA, NA, NA),
                      stringsAsFactors=F)

Is there a way to do this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

One way to do this using merge():

df2Needed <- merge(df2,df1,by="id",all.x=TRUE, sort=FALSE)
df2Needed <- df2Needed[,c("id","value")]
colNames(df2Needed) <- c("id","v2")

and another (more elegant, I think) using match():

df2Needed <- df2
df2Needed$v2 <- df1$value[match(df2$id, df1$id)]

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

...