2013-05-02 34 views
0

我確信這個問題已經在某個地方得到了解答,但是恐怕我不太瞭解R來正確地解決這個問題。將調查數據轉換爲數值

我目前有一個數據集與調查數據答案許多不同的問題。大部分問題都是字符串。我正在將某些列中的某些字符串更改爲數字值,以便我可以將它們繪製在圖上。

具體來說,我的數據集叫做lb2009。一列p10st,提出了3個可能的答案。答案是3種不同的可能句子。我想更改一個句子使其等於1,另一個使其等於2,另一個使其等於3.另一個使其等於3.

如果您可以儘可能輕鬆地爲我拼出這一點,我將不勝感激。謝謝你的幫助。

+0

一個選擇是讀'character'爲'factor',然後可將其轉換爲'numeric'。 – Nishanth 2013-05-02 04:45:08

+0

感謝您的回覆。你能更具體一點嗎? – user2341681 2013-05-02 04:49:45

+0

一個可重複的例子會有所幫助,但無論如何,我試圖回答。 – Nishanth 2013-05-02 05:48:59

回答

0

如何:

sent1 <- lb2009$p10st == 'My first sentence' 
sent2 <- lb2009$p10st == 'My second sentence' 

lb2009[sent1, ] <- 1 
lb2009[sent2, ] <- 2 
lb2009[!sent1 & !sent2, ] <- 3 

這將獲取匹配的句子的行指數前兩句。然後,它設置在特定行中的值1和2的最後一行設置行未句子1和句子不2至3

1

例如,

ans = c("my ans1","my ans2","my ans3") 

as.numeric(factor(ans)) 

## [1] 1 2 3 

注意,大多數文件輸入功能像read.table,read.csv可以選擇將字符串作爲因子。所以你可以使用as.numeric來轉換它們。

0

如果你打開了R,該代碼將正常運行

# look at the full example iris data set (it's pre-loaded in your R) 
iris 

# first six records 
head(iris) 

# convert the `Species` column to numeric, so you get 1, 2, 3 
as.numeric(iris$Species) 

# now actually store that result back on the data frame 
iris$SpeciesCat <- as.numeric(iris$Species) 

# plot your results 
hist(iris$SpeciesCat)