1

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.

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
Yutang Tan
  • 13
  • 2
  • 1
    Could you please copy and paste the current and expected output such that one can know what the aim is before running the code in the question? Also why do you need `attach`? – NelsonGon Aug 30 '19 at 17:34
  • 1
    Try `for(i in seq_len(nrow(kkkk))) {kkkk$new[i] <- kkkk$new[i] + 1; kkkk$leters1[i] <- kkkk$leters1[i] + 1}` In your loop, the `i` is not increased and also not advisable to `attach` – akrun Aug 30 '19 at 17:36

2 Answers2

1

One issue is the 'i' is static at 1 and not changing. It should be increased at the end of the loop i <- i+1. Another option is

for(i in seq_len(nrow(kkkk))) {
      kkkk$new[i] <- kkkk$new[i] + 1
      kkkk$leters1[i] <- kkkk$leters1[i] + 1
  } 
akrun
  • 874,273
  • 37
  • 540
  • 662
1

If one would like to use a non-explicit loop alternative, one could do:

within(kkkk,{ leters1 <- leters1 + 1
            new <- new + 1})
  leters1 leters2 new
1      12      21   1
2      13      22   1
3      14      23   1
4      15      24   1
NelsonGon
  • 13,015
  • 7
  • 27
  • 57