1

I have a data.frame in R and want to fill in some empty cells in specific way. Below is the table.

Case.ID   |   Resource
-----------------------
   1      |     501
-----------------------
   1      | 
-----------------------
   1      |      0
-----------------------
   1      |      
-----------------------
   2      |    524
-----------------------

Here, I want to replace empty cells into the very first value of each Case.ID, in this case replace empty cells with Case.ID = 1 into 501, not 0.

Edward M.
  • 221
  • 1
  • 5
  • 13
  • Please take a look at these tips on how to produce a [minimum, complete, and verifiable example](http://stackoverflow.com/help/mcve), as well as this post on [creating a great example in R](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Perhaps the following tips on [asking a good question](http://stackoverflow.com/help/how-to-ask) may also be worth a read. – lmo May 23 '17 at 12:41
  • Just use `is.na` i.e. `library(data.table); setDT(df1)[, v1 := Resource[1L], Case.ID][is.na(Resource), Resource := v1][, v1 := NULL][]` – akrun May 23 '17 at 12:42

4 Answers4

2

You can use replace in base R,

with(df, ave(v2, v1, FUN = function(i) replace(i, i == '', i[1])))
Sotos
  • 51,121
  • 6
  • 32
  • 66
1

Assuming the blank spaces in your file are being imported as NA, this will work using dplyr

library(dplyr)

# Create data frame to match post
df <- data.frame(Case.ID = c(1, 1, 1, 1, 2),
                 Resource = c(501, NA, 0, NA, 524))

df <- df %>%
  group_by(Case.ID) %>%
  mutate(Resource = if_else(is.na(Resource), head(Resource, 1), Resource))

df
# Case.ID Resource
# <dbl>    <dbl>
#    1      501
#    1      501
#    1        0
#    1      501
#    2      524
MeetMrMet
  • 1,349
  • 8
  • 14
1

We can use data.table

library(data.table)
setDT(df1)[, v1 := Resource[1L], Case.ID][is.na(Resource), Resource := v1][, v1 := NULL][]  

Or another option is na.aggregate

library(zoo)
setDT(df)[, Resource := na.aggregate(Resource, FUN = function(x) x[1]), Case.ID]
akrun
  • 874,273
  • 37
  • 540
  • 662
1

as soon as you import it in R (let's say df) the empty ones are transformed into NA's. Hence:

  Case.ID Resource
1       1      501
2       1       NA
3       1        0
4       1       NA
5       2      524

Therefore:

df$Resource<-ifelse(is.na(df$Resource),df$Case.ID,df$Resource)

yielding:

Case.ID Resource
1       1      501
2       1        1
3       1        0
4       1        1
5       2      524
amonk
  • 1,769
  • 2
  • 18
  • 27