2014-02-09 85 views
0

假设我有以下数据集。在'R'中实现代码?

Index-----Country------Age------Time-------Response 
--------------------------------------------------- 
1------------------Germany-----------20-30----------15-20------------------1 

2------------------Germany-----------20-30----------15-20------------------NA 

3------------------Germany-----------20-30----------15-20------------------1 

4------------------Germany-----------20-30----------15-20------------------0 

5------------------France--------------20-30----------30-40------------------1 

而且我想基于以下

  1. 所列的标准查找的国家,年龄和时间都精确匹配填写NA。即。索引1,3和4
  2. 从这些匹配的 行的响应列中随机选择一个值。即1,1或0
  3. 更换NA与这个新的价值

而且我想它继续以同样的方式进行的NA的数据集的其余部分。

我是'R'的新手,无法弄清楚如何对其进行编码。

+0

请提供一个可重现的例子。 –

+0

你想用数据中的所有减号做什么? – Spacedman

回答

2

下面是使用 “data.table” 包一个做法:

DT <- data.table(mydf, key = "Country,Age,Time") 
DT[, R2 := ifelse(is.na(Response), sample(na.omit(Response), 1), 
        Response), by = key(DT)] 
DT 
# Index Country Age Time Response R2 
# 1:  5 France 20-30 30-40  1 1 
# 2:  6 France 20-30 30-40  NA 2 
# 3:  7 France 20-30 30-40  2 2 
# 4:  1 Germany 20-30 15-20  1 1 
# 5:  2 Germany 20-30 15-20  NA 1 
# 6:  3 Germany 20-30 15-20  1 1 
# 7:  4 Germany 20-30 15-20  0 0 

同样,在基础R,你可以尝试ave

within(mydf, { 
    R2 <- ave(Response, Country, Age, Time, FUN = function(x) { 
    ifelse(is.na(x), sample(na.omit(x), 1), x) 
    }) 
}) 

对不起,忘分享我正在使用的示例数据:

mydf <- structure(list(Index = 1:7, Country = c("Germany", "Germany", 
"Germany", "Germany", "France", "France", "France"), Age = c("20-30", 
"20-30", "20-30", "20-30", "20-30", "20-30", "20-30"), Time = c("15-20", 
"15-20", "15-20", "15-20", "30-40", "30-40", "30-40"), Response = c(1L, 
NA, 1L, 0L, 1L, NA, 2L)), .Names = c("Index", "Country", "Age", 
"Time", "Response"), class = "data.frame", row.names = c(NA, -7L))