I want to add a new column to an existing data frame using "for loops", before the "for loops", I declare a new column and use attach() function to include the data frame, what I thought is that I can change the values by citing the colname,however, just new variables similar to the colnames are created, the data frame didn't make any change, what's wrong?
first, I checked the data type, it's right. second, I checked the variables in the environment, nothing wrong. I also checked the variable scope, can't find any problem.
kkkk<- data.frame(leters1 = c(11,12,13,14),leters2 = c(21,22,23,24))
kkkk$new<- vector("numeric",4)
attach(kkkk)
i=1
for (i in (1:4)) {
new[i]<- new[i]+1
leters1[i]<- leters1[i]+1
}
new
leters1
leters2
kkkk
detach(kkkk)
new
leters1
leters2
before detach,i expect the new (1,1,1,1),leters(12,13,14,15),kkkk(12,13,14,15;21,22,23,24;1,1,1,1)
after the detach, I expect the new, leters1,leters2 to be warnings (object not found). but the actual is that the data frame didn't make any change, and two variables (new, leters1) are created in the global environment.