0

Just like the title, I would like to replace certain cells in a data.frame which is accessed through get, a reproducible example to clarify my question:

df <- data.frame( x = rnorm(10),
                  y = rnorm(10))

I want to replace, say the first element of column x, in df as 'A', which is quite easy in the common ways:

df[1,'x']<-NA

However, how could I do this if I have to access df through another function like get, what I want to do is something like:

get('df')[1,'x']<-NA

which will throw out an error: target of assignment expands to non-language object. I searched here and other places on Google for a while, a similar question here, but no solution so far. Is this possible? How if it is.

============ EDIT based on MKR's comment =============== here is the solution:

a<-get('df')
a[1,'x']<-NA
assign('df',a)
rm(a)
Jason Goal
  • 1,014
  • 2
  • 11
  • 23
  • 1
    `get` function return the `df` and your code `get('df')[1,'x'] – MKR Apr 15 '18 at 07:32
  • 1
    @MKR, did you try my code? it did not work on my machine. And one can't assign a value to an object returned by another function I guess. – Jason Goal Apr 15 '18 at 07:36
  • What exactly I meant was that `get('df')` will give you `df` and then you can modify it per your choice. For example `a – MKR Apr 15 '18 at 07:41
  • Having to use `get` often suggests you should be storing things in a list instead of as separate objects. Can you give some context for your question? –  Apr 15 '18 at 07:46
  • @MKR, yeah, that's a way doing it, sorry for my misunderstanding. I must have myself a cup of coffee to avoid such silly questions. I will re-edit the question based on your comment. Btw, is there a one-liner of this problem? – Jason Goal Apr 15 '18 at 07:49
  • @JasonGoal There can be couple of options to apply `% mutate(x = ifelse(row_number()==1, NA, x))` – MKR Apr 15 '18 at 07:52
  • It is better to add your answer as an "answer" rather than in the question. –  Apr 15 '18 at 07:57
  • @dash2, you are correct on the `list` instead of `get` point, agree with you. I'm modifying an old stuff written years back. – Jason Goal Apr 15 '18 at 07:58
  • @dash2, sure, if MKR is willing to post an answer, I would like to accept it and delete the solution part from my question. If not, I would like to keep it in the question, as the credit is not mine. – Jason Goal Apr 15 '18 at 08:01
  • `assign('df', \`[ – CJ Yetman Apr 15 '18 at 10:58

0 Answers0