Replace rows in a dataframe by matching individual rows of another dataframe in R -
i've 2 dataframes , want replace rows of first dataframe inserting rows of second dataframe. following did until now, not result want have.
df1 <- data.frame(a = c(0, 0,0,0 ,1, 1, 1, 2, 2), b = rep(0, 9)) df2 <- data.frame(a = c(1, 1), b = rep(1, 2)) df1[match(df2$a, df1$a), ] <- df2 > df1 b 1 0 0 2 0 0 3 0 0 4 0 0 5 1 1 6 1 0 7 1 0 8 2 0 9 2 0
what want have dataframe adopts second row of df2 , looks following:
> df1 b 1 0 0 2 0 0 3 0 0 4 0 0 5 1 1 6 1 1 7 1 0 8 2 0 9 2 0
is there function kind of matching?
the point have rows(5,6,7) identical values:
> which(df1$a %in% df2$a) [1] 5 6 7 > df1[which(df1$a %in% df2$a),] b 5 1 0 6 1 0 7 1 0
so if join or replace, 1 condition not enough replace rows 5,6 , exclude 7 in desired result.
if want replace n rows, n=the number of rows in df2, can use following. replace first 2 rows a=1.
df1[which(df1$a %in% df2$a)[1:nrow(df2)],] <- df2 > df1 b 1 0 0 2 0 0 3 0 0 4 0 0 5 1 1 6 1 1 7 1 0 8 2 0 9 2 0
Comments
Post a Comment