2013-12-18 79 views
1

我是一個新的初學者學習R.我的問題應該與R的工作空間或創建一個因子變量或兩者都有關。這裏是我的問題:我用這個語法來打開標題爲「lecturerData」 csv文件:R工作空間和從數字變量創建因子變量

lecturerData <- read.csv("Lecturer Data.csv" , header = TRUE) 

此文件已列標題有兩個neumwric值的「工作」:1和2。我想改變這些值作爲因子變量,以便1代表講師,2代表學生。所以,我用這個語法:

job <- factor (job, levels = c(1:2), labels=c("Lecturer","Student"))

但我收到此錯誤信息:

object 'job' not found 

然後,我改變上述語法:

lecturerData$job <- factor (lecturerData$job, levels = c(1:2), 
          labels=c("Lecturer","Student")) 

和它的作品。我覺得我在這裏錯過了一些東西。

希望你的幫助。

+0

也許你應該選擇一個答案,並接受它! – marbel

回答

0

job <- factor (job, levels = c(1:2), labels=c("Lecturer","Student")) 

你試圖調用尚未創建解釋錯誤的變量。

如果你不喜歡的東西

job <- lecturerData[,(inserts column number for job)] 

然後運行上面的代碼應該解決您的問題

希望它有助於

0

下面是如何創建一個data.frame再舉幾個例子factor()變量。

# Create a data frame 

df <- data.frame(x = 1:1000, y = rnorm(1000, 100, 20)) 

# Take a look at it 
head(df) 
names(df) 
str(df) 

# Convert a numerical variable to a factor variable 
# check out ?cut 
# also ?rnorm 

df$z <- cut(df$y, breaks = c(0, 50, 100, 200, 1000000)) 

df$binary <- ifelse(df$y < 100, 1 , 0) 

str(df) 
# Now binary is numeric 
# If i just type binary i'm R doesn't know in which data.frame it is. 

df$binary_factor <- factor(df$binary, levels = 1:2, labels = c("lecturer", "student")) 

# Take a look at it again 
head(df) 
names(df) 
str(df) 

# Agreggate 
# Check out ?table 

table <- table(df$z) 

plot(df$z) 

library(ggplot2) 
qplot(df$y, binwidth = 0.5, fill = df$z) 
qplot(df$z, fill = df$z) 
0

您也可以使用變換(),以避免不得不做$語法:

lecturerData <- transform(lecturerData, 
    job = factor(job, levels = c(1:2), labels=c("Lecturer","Student")) 
)