Search code examples
rfunctiondataframepositionassign

Change dataframe values R using different column name provided?


I have the following data frame:

     Column1 Default_Val
1          A           2
2          B           2
3          C           2
4          D           2
5          E           2
...
colnames: "Column1" "Default_Val"
rownames: "1"  "2"  "3"  "4"  "5"

This data frame is part of my function and this function changes the default values according to some if's.

I want to generalize the assignment process because I want to support different column names of this data frame.

Please advise how can I change the default value without being dependent of column names?

Here is what I did so far:

df[Column1 == "A","Default_Val"]
[1] 2
df[Column1 == "A","Default_Val"] = 2
df[Column1 == "A","Default_Val"]
[1] 1

I want something generalized like:

t <- colnames(df)
df[t[1] == "A", t[2]] = 7

For some reason it doesn't work (each time this happens I love Python more :)).

Please advise.


Solution

  • I think it must be straightforward. Please check if this solves your problem.

    > df
      Column1 Default_val
    1       A           1
    2       B           3
    3       A           4
    4       C           1
    5       D           4
    > df[2][df[1] == 'A'] = 3
    > df
      Column1 Default_val
    1       A           3
    2       B           3
    3       A           3
    4       C           1
    5       D           4