Reputation: 1079
I have a dataframe:
df <- data.frame(id = c('1','2','3'), b = c('b1', '', 'b3'), c = c('c1', 'c2', ''), d = c('d1', '', ''))
id b c d
1 b1 c1 d1
2 c2
3 b3
where the row with id-1
is filled with all data with no empty column values. I want to copy all cell values from id-1
into id 2 and 3
if there are missing values in those cells from rows 2 & 3
. Final output something like:
df2 <- data.frame(id = c('1','2','3'), b = c('b1', 'b1', 'b3'), c = c('c1', 'c2', 'c1'), d = c('d1', 'd1', 'd1'))
id b c d
1 b1 c1 d1
2 b1 c2 d1
3 b3 c1 d1
Thank you for your help in advance
Upvotes: 1
Views: 303
Reputation: 93938
Use some matrix indexing to get the ""
cases and then overwrite selecting the appropriate column from the first row of df
:
idx <- which(df[-1]=="", arr.ind=TRUE)
df[-1][idx] <- unlist(df[1,-1][idx[,"col"]])
# id b c d
#1 1 b1 c1 d1
#2 2 b1 c2 d1
#3 3 b3 c1 d1
Upvotes: 1