2013-07-16 53 views
0

我非常感謝任何人在解決此問題時提供的幫助。這是很多要問,所以任何和所有的建議表示讚賞!R代碼,根據條件創建新列數

下面是@dardisco在一個月前詢問類似問題時創建的示例集。 a和b代表兩個不同的測試,數字(09,10,11)表示測試完成的年份。

最後,我想弄清楚

  1. 陽性B號測試的正性A /測試次數,2010年和2011年

  2. 的陽性B試驗次數/ B總數測試中,2010年和2011年,我必須先檢查

幾件事情:

  • 如果2009年和2010年都進行了A測試,我會從2010年開始測試。對於B測試也是如此。
  • 我想刪除任何有人進行B測試但沒有先測試一下。如果它在同一年就沒關係。不應該有任何這些...但我想知道如何檢查。

如果有人有任何建議,我會很感激!如果你只是想解決問題的一部分(無論我最終想要弄清楚什麼,或者我想先做的檢查),那就太棒了。我不確定我是否應該使用嵌套ifelse語句,或者如果別的東西會更好...

如果您需要更多信息,請告訴我!

vals1 <- c(NA, "pos", "neg", "nr") 
set.seed(1) 
df1 <- data.frame(
    id = seq(1:10), 
    a09 = sample(vals1,10,replace=TRUE), 
    a10 = sample(vals1,10,replace=TRUE), 
    a11 = sample(vals1,10,replace=TRUE), 
    b10 = sample(vals1,10,replace=TRUE), 
    b11 = sample(vals1,10,replace=TRUE) 
    ) 

### modify to give at least one case meeting each of your criteria 
df1[10,c(5,6)] <- NA # 2x NAs for b's 
df1[1,c(2,3,4)] <- NA # 3x NAs for a's 
df1[2,c(2,4,5,6)] <- NA # all NAs 

回答

0

對於第一個問題確定:如果我理解正確的話,您只想考慮最近的A和b測試。對?

# a by default the 2011-a 
df1$a=df1$a11 
# if currently not defined set a to 2010-a 
df1[ is.na(df1$a), "a"] = df1[ is.na(df1$a), "a10"] 

# b by default 2011 b 
df1$b=df1$b11 
# if not defined yet set b to 2010-b 
df1[ is.na(df1$b), "b"] = df1[ is.na(df1$b), "b10"] #set just those a's to 10 not defined in a11 

# set all b's to NA where a is NA 
df1[is.na(df1$a), "b"] = NA 

# number of positive a's 
num.pos.a = nrow(df1[ !is.na(df1$a) & df1$a=="pos",]) 
# number of positive b's 
num.pos.b = nrow(df1[ !is.na(df1$b) & df1$b=="pos",]) 

是你想要的嗎?

+0

這看起來像我想要的,但我還沒有能夠得到它的工作。我會繼續玩,謝謝。 – user2494353

相關問題