我想在apply
內使用ifelse
聲明,並得到一個奇怪的結果。如果變量是1
,我會得到預期的答案,但當變量爲> 9
時,則不會。ifelse聲明裏面申請返回意外的結果
下面是一個例子的數據集用於我得到正確的答案:
my.data <- read.table(text = '
REFNO status stage marker cumulative newstage
1018567 ccc AA 0 1 AA
1018567 aaa NONE 0 1 NONE
1018567 aaa BB 1 1 BB
1018567 bbb CC 1 1 CC
1018567 eee CC 1 1 CC
1018567 mmm CC 1 1 CC
1018567 ppp CC 1 1 CC
1019711 ddd CC 1 1 CC
', header = TRUE, stringsAsFactors = FALSE)
my.data$newstage <- apply(my.data, 1, function(x) ifelse(x['status'] == 'aaa' &
x['stage'] == 'NONE' &
x['marker'] == 0 &
x['cumulative'] > 0, 'BB', x['stage']))
my.data
下面的數據設置爲從與上面只有一個元素不同,但我不獲得正確的答案。
my.data <- read.table(text = '
REFNO status stage marker cumulative newstage
1018567 ccc AA 0 1 AA
1018567 aaa NONE 0 1 NONE
1018567 aaa BB 1 1 BB
1018567 bbb CC 1 1 CC
1018567 eee CC 1 1 CC
1018567 mmm CC 1 1 CC
1018567 ppp CC 1 1 CC
1019711 ddd CC 14 1 CC
', header = TRUE, stringsAsFactors = FALSE)
my.data$newstage <- apply(my.data, 1, function(x) ifelse(x['status'] == 'aaa' &
x['stage'] == 'NONE' &
x['marker'] == 0 &
x['cumulative'] > 0, 'BB', x['stage']))
my.data
謝謝你的任何建議。也許我應該使用if
而不是if-else
?
具體而言,我希望NONE
在第二行中替換爲BB
爲newstage
。
不知道這是否是問題,但如果你看看'申請(my.data2,1,函數( x)x)'由於標記列中的兩位數字14,標記列有兩個字符而不是一個字符。這會在你的代碼中產生「0」== 0,這是'FALSE'。但是,'「0」== 0'是'TRUE' – 2014-09-25 17:08:47
爲什麼你不能使用'with(my.data,ifelse(status =='aaa'&stage =='NONE'&!marker&cumulative> 0 ,'BB',stage))' – akrun 2014-09-25 17:17:15