0

I have the following data.table:

name = c("Bob","Mary","Jane","Kim")
weight = c(60,65,45,55)
height = c(170,165,140,135)
dft = data.table(name,weight,height)

I want to change weight to be equal to height + 13 . I know numerous ways can do this, for example

dft[, weight := height + 13

or

dft[, "weight" := height + 13

However, since I have a huge dataset whose column names are like V1, V2,....,V1000, I wish to use column names to enter modification. In the above example, however,

dft[, "weight" := "height" + 13

is not working.

So I wonder how to use "height" to modify weight. Thanks

Henrik
  • 65,555
  • 14
  • 143
  • 159
tobinz
  • 305
  • 1
  • 7

2 Answers2

1

You can use :

library(data.table)
name = c("Bob","Mary","Jane","Kim")
weight = c(60,65,45,55)
height = c(170,165,140,135)
dft = data.table(name,weight,height)

col1 <- 'weight'
col2 <- 'height'

dft[, (col1) := get(col2) + 13]
dft

#   name weight height
#1:  Bob    183    170
#2: Mary    178    165
#3: Jane    153    140
#4:  Kim    148    135
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
-2

I find data.table to be awful on so many levels.

In base R you would just need:

df[, 'height'] + 13 -> df[, 'weight' ]
Justin Cocco
  • 392
  • 1
  • 6