Reputation: 63
age <- seq(10, 100, 10)
df <- data.frame(age)
df
this doesnt work
df$agegroup <- vector(mode = "character", length = nrow(df))
attach(df)
agegroup[age >= 10 & age < 20] <- "10To20"
detach(df)
df$agegroup
this works fine
df$agegroup <- vector(mode = "character", length = nrow(df))
df$agegroup[df$age >=10 & df$age < 20] <- "10To20"
df$agegroup
Can somebody explain why is that? thank you!
Upvotes: 0
Views: 725
Reputation:
As mentioned in the documentation of attach
:
The database is not actually attached. Rather, a new environment is created on the search path and the elements of a list (including columns of a data frame) or objects in a save file or an environment are copied into the new environment. If you use
<<-
orassign
to assign to an attached database, you only alter the attached copy, not the original object. (Normal assignment will place a modified version in the user's workspace: see the examples.) For this reasonattach
can lead to confusion.
Upvotes: 4