df2 <- data.frame(Mean = c(.5,4,2.3,1.2,3.7,3.3,.8), Numbers = "NA")
for(i in 1:length(df2$Mean)){
if(df2$Mean[i] <= .5) {
df2$Number[i] = 0
}
else if(df2$Mean[i] > .5 & df2$Mean[i] < 1.5){
df2$Number[i] = 1
}
else if(df2$Mean[i] > 1.5 & df2$Mean[i] < 2.5){
df2$Number[i] = 2
}
else if(df2$Mean[i] > 2.5 & df2$Mean[i] < 3.5){
df2$Number[i] = 3
}
else {
df2$Number[i] = 4
}
}
这行得通!但是,当我尝试从中创建一个函数并调用该函数时,它不起作用。我将函数文件保存为“df2type.txt”:
type <- function(df2){
for(i in 1:length(df2$Mean)){
if(df2$Mean[i] <= .5) {
df2$Number[i] = 0
}
else if(df2$Mean[i] > .5 & df2$Mean[i] < 1.5){
df2$Number[i] = 1
}
else if(df2$Mean[i] > 1.5 & df2$Mean[i] < 2.5){
df2$Number[i] = 2
}
else if(df2$Mean[i] > 2.5 & df2$Mean[i] < 3.5){
df2$Number[i] = 3
}
else {
df2$Number[i] = 4
}
}
}
我将函数调用为:
source("df2type.txt")
type(df2)
你能告诉我为什么这个功能不起作用吗?
太感谢了!