Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R assign column to dataframe with variable name

Tags:

syntax

r

Assign to a dataframe colum with a variable name.

getModified <- function(dframe, destination_string, foo, bar) {
    # complex calculations on foo and bar getting mynewcol here
    # ...

    # I want to add mynewcolumn with name in destination_string
    # if "blah" was the destination_string, the result would be as:
    #dframe$blah <- mynewcol
    #return(dframe)

    # what is the syntax for using the variable?
    # no luck here:
    dframe[, destination_string] <- mynewcolumn
    return(dframe)
  }

so that I could call

dframe <- getModified(dframe, "nameofmynewcolum", foo, bar)
dframe$nameofmynewcolumn
like image 927
Skylar Saveland Avatar asked Oct 25 '25 14:10

Skylar Saveland


1 Answers

The syntax is

dframe[[destination_string]] <- mynewcolumn

For example,

getModified <- function(dframe, destination_string, foo) {
  dframe[[destination_string]] <- foo
  dframe
}
>     getModified(data.frame(A=1:10), "newColName", 11:20)
    A newColName
1   1         11
2   2         12
3   3         13
4   4         14
5   5         15
6   6         16
7   7         17
8   8         18
9   9         19
10 10         20
like image 156
GSee Avatar answered Oct 28 '25 04:10

GSee