user13467695
user13467695

Reputation:

How to replace one column with another using data.table?

I have a dataframe:

ID      value1   value2
1        f        a
2        k        p
3        c        j

I want to replace values in column value1 with values from value2 and remove column value2. So desired result is:

ID      value1   
1        a        
2        p        
3        j        

I need to do it with data.table. And i need to do it with function, not recreating dataframe from scratch.

Upvotes: 1

Views: 499

Answers (4)

akrun
akrun

Reputation: 886938

Using dplyr

library(dplyr)
df %>%
   select(ID, value1 = value2)

data

df <- structure(list(ID = 1:3, value1 = c("f", "k", "c"), value2 = c("a", 
"p", "j")), class = "data.frame", row.names = c(NA, -3L))

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101034

You can do something like below

> setDT(df)[, .(ID, value1 = value2)]
   ID value1
1:  1      a
2:  2      p
3:  3      j

Data

> dput(df)
structure(list(ID = 1:3, value1 = c("f", "k", "c"), value2 = c("a", 
"p", "j")), class = "data.frame", row.names = c(NA, -3L))

Upvotes: 1

s_baldur
s_baldur

Reputation: 33498

library(data.table)
setDT(df)
df[, c("value1", "value2") := .(value2, NULL)]

Or with setnames()

df[, value1 := NULL]
setnames(df, "value2", "value1")

Data

df <- data.frame(
  ID = 1:3, value1 = c("f", "k", "c"), value2 = c("a", "p", "j")
)

Upvotes: 3

Ronak Shah
Ronak Shah

Reputation: 388807

With data.table you can do :

library(data.table)
setDT(df)
df[, value1:=value2][, value2:=NULL]

Upvotes: 2

Related Questions