Move the last observation of the factor back and forth in the row group to R

Suppose I have a dataset that looks like

ID Name 
1  JAY
1  
1  JAY
2  LAY
2  LAY
2  
3  NA
3  KAY
3  

I want to fill rows with missing values ​​(empty or with NA) based on the observation already available in the group. Thus, the resulting data frame will look like

ID Name 
1  JAY
1  JAY
1  JAY
2  LAY
2  LAY
2  LAY
3  KAY
3  KAY
3  KAY

I tried to use na.locf, but it did not work for a non-numeric value.

DF1 = setDT(DF)[,  N := na.locf(na.locf(Name(NA_real_^!Name),na.rm=FALSE), fromLast=TRUE, na.rm=FALSE), ID][is.na(N), N := 0]
+2
source share
3 answers

One option - after grouping by "ID", a subset of "Name" that are not NA, but not empty ( nzchar(Name)), get the last observation ( tail(...)) and assign ( :=) this "Name".

setDT(DF)[, Name := tail(Name[!is.na(Name) & nzchar(Name)], 1), by = ID]
DF
#   ID Name
#1:  1  JAY
#2:  1  JAY
#3:  1  JAY
#4:  2  LAY
#5:  2  LAY
#6:  2  LAY
#7:  3  KAY
#8:  3  KAY
#9:  3  KAY

"" factor nzchar(Name) nzchar(as.character(Name))


"i" (:=) (Name[.N]) "" "ID"

setDT(DF)[!is.na(Name) & nzchar(Name), Name := Name[.N], ID]

. 'Name' character.

+3

R ( split do.call(bind, ...). , d dataframe:

tmp <- lapply(split(d, d$ID), function(x) { 
    # Explanation:
    # decreasing = TRUE so that empty strings are at the end
    # na.last = NA so that NA are omitted
    x$Name <- sort(x$Name, decreasing = TRUE, na.last = NA)[1];
    return(x);
})

d.new <- do.call(rbind, tmp);

print(d.new);
ID Name
1.1  1  JAY
1.2  1  JAY
1.3  1  JAY
2.4  2  LAY
2.5  2  LAY
2.6  2  LAY
3.7  3  KAY
3.8  3  KAY
3.9  3  KAY
+2

na.locf , , data.table . , , .

:

df <- data.frame('ID' = c(1,1,1,2,2,2,3,3,3),
                 'Name' = c('JAY', '', 'JAY', 'LAY', 'LAY', '', NA, 'KAY', ''),
                 stringsAsFactors = FALSE)

df$Name <- na.locf(df$Name, fromLast = TRUE) # takes care of 'KAY'    

df[df==''] <- NA

df$Name <- na.locf(df$Name) # takes care of the rest

R- , ID , . - () .

0
source

Source: https://habr.com/ru/post/1672768/


All Articles