Digvijay Sawant
Digvijay Sawant

Reputation: 1079

Copy selective row values from 1 dataframe to another in R

I have a dataframe:df <- data.frame(id = c('1','2','3'), b = c('b1', 'NA', 'b3'), c = c('c1', 'c2', 'NA'), d = c('d1', 'NA', 'NA'))

id b   c   d
1  b1  c1  d1
2  NA  c2  NA
3  b3  NA  NA

I have extracted values with id = 1 from df to another dataframe say df2 so df2 has 1 row

id b c d
1 b1 c1 d1

I need to copy all values from df2 to df1 wherever there is not an NA in df1 Result Table:

id b   c   d
1  b1  c1  d1
2  b1  c2  d1
3  b3  c1  d1

Thank you in advance. I asked similar question before but deleting it.

Upvotes: 0

Views: 409

Answers (2)

hpesoj626
hpesoj626

Reputation: 3629

Based on your last comment that df2[3,3] should be c2 and not c1, a straightforward answer is to use zoo::na.locf.

library(zoo)
df2 <- na.locf(df)

#   id  b  c  d
# 1  1 b1 c1 d1
# 2  2 b1 c2 d1
# 3  3 b3 c2 d1

Data

df <- structure(list(id = c(1, 2, 3), b = c("b1", NA, "b3"), c = c("c1", 
"c2", NA), d = c("d1", NA, NA)), class = "data.frame", row.names = c(NA, 
-3L))

Upvotes: 1

Resham Wadhwa
Resham Wadhwa

Reputation: 129

Assuming that there is a mistake in your question -> df2 will be equal to b1-c1-d1 not b1-c2-d1, here is the solution :

Initialize dataframe

df <- data.frame(id = c('1','2','3'), b = c('b1', 'NA', 'b3'), c = c('c1', 'c2', 'NA'), d = c('d1', 'NA', 'NA'))

Converting string NAs to actual detectable NAs

df <- data.frame(lapply(df, function(x) { gsub("NA", NA, x) }))

Obtaining default value row

df2<-df[df$id==1,]

For all rows, check if the column cell is na, then fill it with the df2 cell of the same column

for (r in 1:nrow(df)) for( c in colnames(df)) df[r,c]<-ifelse(is.na(df[r,c]),as.character(df2[1,c]),as.character(df[r,c]))

Upvotes: 1

Related Questions