1

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.

4 Answers 4

3
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")
)
Sign up to request clarification or add additional context in comments.

1 Comment

Your first approach is cool! Upvoted your answer.
2

With data.table you can do :

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

Comments

1

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))

Comments

1

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.