R - How to conditionally set multiple values ​​in a vector based on a single current value

I have a dataset similar to the example below. What I want to do is assign all missing values ​​the correct "Name" value based on the missing values ​​and the associated "Name". Thus, all entries with the name β€œA” will have the title β€œX” and similar for B and β€œY”.

Name | Title
-------------
A    |  X
A    |  NA
A    |  NA
B    |  NA
B    |  Y
B    |  Y

For each "name" there should be only one value "Name", although this one value can appear several times.

I suppose there are some painful conditional loops that could achieve this, but I'm curious if there are any more neat / more efficient ways to do this?

+4
3

, :

lu <- unique(df[complete.cases(df),])         ## Make a look-up table
df$Title <- lu$Title[match(df$Name, lu$Name)] ## Use it to find Name-->Title mappings

## Check that it worked
df
#   Name Title
# 1    A     X
# 2    A     X
# 3    A     X
# 4    B     Y
# 5    B     Y
# 6    B     Y
+5

, na.locf zoo:

library(zoo)
na.locf(mydf[order(mydf$Name, mydf$Title),])

  Name Title
1    A     X
2    A     X
3    A     X
5    B     Y
6    B     Y
4    B     Y
+3

Title, NA, .

a dplyr :

dt = data.frame(Name = c("A","A","A","B","B","B"),
                Title = c("X",NA,NA,NA,"Y","Y"),
                stringsAsFactors = F)

library(dplyr)

dt %>% group_by(Name) %>%
  do(data.frame(Name = .$Name,
                Title2 = unique(.$Title[!is.na(.$Title)]),
                stringsAsFactors=F)) %>%
  ungroup

#     Name Title2
#    (chr)  (chr)
# 1     A      X
# 2     A      X
# 3     A      X
# 4     B      Y
# 5     B      Y
# 6     B      Y

data.table:

dt = data.frame(Name = c("A","A","A","B","B","B"),
                Title = c("X",NA,NA,NA,"Y","Y"),
                stringsAsFactors = F)

library(data.table)

dt = setDT(dt)

dt[, Title2 := unique(Title[!is.na(Title)]), by="Name"][,Title:=NULL]
dt

#    Name Title2
# 1:    A      X
# 2:    A      X
# 3:    A      X
# 4:    B      Y
# 5:    B      Y
# 6:    B      Y

, , , - , .

+2

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


All Articles