如何添加像字典一样的键值对?

时间:2017-09-03 09:47:02

标签: r list for-loop missing-data

我的数据(总共8532个障碍物)看起来像这样:

Prd_Id  Weight
DRA24   19.35
DRA24   NA
DRA24   NA
DRA24   19.35
DRA24   19.35
DRA59   8.27
DRA59   8.27
DRA59   8.27
DRA59   8.27
DRA59   NA
DRA59   NA

基本上问题是有很多Prd_idweight对,其中一些Prd_id没有提到weight,例如我在第一个但第二个和第三个的数据不是这样我知道weight的值,我只需要用它替换NA,所有相同的Prd_id将具有相同的weight但在R中没有像字典这样的东西,所以我发现很难解决这个问题。我尝试使用for loop但是需要很长时间,我的代码看起来像这样:

for(i in 1:nrow(bms)){
  for(j in 1:1555){
    if(spl$Prd_Id[j]==bms$Prd_Id[i]){
      bms$weight[i]=spl$weight[j]
    }
  }
}

bms是整个data(8532个障碍物),spl(1555个障碍物)是bms的子集,其唯一值为Prd_Id。< / p>

3 个答案:

答案 0 :(得分:1)

正如@ r2evans建议您可以使用类似SQL的连接策略,结合dplyr的coalesce,这看起来像这样:

library(dplyr)

# create 'bms'.
bms <- data_frame(
  Prd_Id = c("DRA24", "DRA24", "DRA24", "DRA24", "DRA24", "DRA59", "DRA59", "DRA59", "DRA59", "DRA59", "DRA59"),
  Weight = c(19.35, NA, NA, 19.35, 19.35, 8.27, 8.27, 8.27, 8.27, NA, NA)
)

# create 'spl'
spl <- bms %>% filter(!is.na(Weight)) %>% filter(!duplicated(Prd_Id))

# SQL-like join and coalesce strategy
res <- bms %>% 
  left_join(spl, by = "Prd_Id", suffix = c("_bms", "_spl")) %>% 
  mutate(Weight = coalesce(Weight_bms, Weight_spl)) %>%
  select(-Weight_bms, -Weight_spl)

答案 1 :(得分:1)

无需left_join

bms %>% 
  group_by(Prd_Id) %>% 
  mutate(Weight = Weight[!is.na(Weight)][1])

first的另一种方式:

bms %>% 
  group_by(Prd_Id) %>% 
  mutate(Weight = first(Weight[!is.na(Weight)]))

结果:

# A tibble: 11 x 2
# Groups:   Prd_Id [2]
   Prd_Id Weight
    <chr>  <dbl>
 1  DRA24  19.35
 2  DRA24  19.35
 3  DRA24  19.35
 4  DRA24  19.35
 5  DRA24  19.35
 6  DRA59   8.27
 7  DRA59   8.27
 8  DRA59   8.27
 9  DRA59   8.27
10  DRA59   8.27
11  DRA59   8.27

当然,你也可以在香草R中做到这一点:

transform(bms, Weight = ave(Weight, Prd_Id, FUN = function(x) x[!is.na(x)][1]))

结果是一样的:

   Prd_Id Weight
1   DRA24  19.35
2   DRA24  19.35
3   DRA24  19.35
4   DRA24  19.35
5   DRA24  19.35
6   DRA59   8.27
7   DRA59   8.27
8   DRA59   8.27
9   DRA59   8.27
10  DRA59   8.27
11  DRA59   8.27

答案 2 :(得分:0)

这是基础R解决方案

# example data
bms <- data.frame(
  Prd_Id = c("DRA24", "DRA24", "DRA24", "DRA24", "DRA24", "DRA59", "DRA59", "DRA59", "DRA59", "DRA59", "DRA59"),
  Weight = c(19.35, NA, NA, 19.35, 19.35, 8.27, 8.27, 8.27, 8.27, NA, NA)
)

# create key-value pairs
spl <- unique(bms[!is.na(bms[,"Weight"]),])
spl <- setNames(spl[,"Weight"], spl[,"Prd_Id"])

# fill NAs
idx <- which(is.na(bms[,"Weight"]))
bms[idx,"Weight"] <- spl[bms[idx, "Prd_Id"]]