2013-10-28 97 views
0

應該如何輸入字符因子的一個級別中的引號,以使得結果數值包含1,2或3的值(對於「既不是」又不是「b」)?下面的兩個嘗試沒有給我想要的結果。謝謝。R:字符因子中的引號

> table(MM2$a.9) 

      FALSE Neither 「a」 or 「b」    TRUE 
       34     90    583 
> MM2$a04f <- as.numeric(factor(MM2$a.9, levels=c ('TRUE','FALSE','Neither 「a」 or 「b」'))) 
> table(MM2$a04f) 

    1 2 
583 34 
> MM2$a04f <- as.numeric(factor(MM2$a.9, levels=c ("TRUE","FALSE","Neither \"a\" or \"b\""))) 
> table(MM2$a04f) 

    1 2 
583 34 
+0

你可以發佈一些模擬數據嗎? – Heisenberg

+1

你可以嘗試將該列重命名爲簡單的東西嗎? – beroe

回答

0

(我張貼此爲「答案」,即使這真是一個評論......就這樣我可以有超過我張貼更好的控制代碼。)

我創建了一些虛假的數據,你的第二種方法在它上面工作。

df <- structure(list(x = c("TRUE", "FALSE", "Neither \"a\" nor \"b\"", 
    "TRUE", "FALSE", "Neither \"a\" nor \"b\"", "TRUE", "FALSE", 
    "Neither \"a\" nor \"b\"")), .Names = "x", class = "data.frame", 
    row.names = c(NA, -9L)) 
df 
df$x 
table(df$x) 
table(as.numeric(factor(df$x, levels=c("TRUE", "FALSE", "Neither \"a\" nor \"b\"")))) 

我建議你使用dput()來共享您的數據幀或列表的一小部分,所以我們有東西出來的測試方法。例如,如果在數據框的前六行中有「既不是」也不是「b」「的記錄,這將起作用。

dput(head(MM2))