-1

I have a data.table (dataframe). Can I create a new column with certain values based on another columns (based on the column like the picture below)?

For example, can I create a new column named A, with values = c (1.2,5.6,10.3,20.4), and make it be corresponding to S4,S9,S5,S10 in column stimulus?

enter image description here

Kenny
  • 361
  • 1
  • 8

1 Answers1

0

An easier option is to convert to factor with levels specified as unique elements of the column and coerce to integer with as.integer

df1$A <- as.integer(factor(df1$stimulus, levels = unique(df1$stimulus)))

Or use match on the unique values

df1$A <- with(df1, match(stimulus, unique(stimulus)))

-Update

If it needs to be custom values, an option is also to specify the labels along with levels

df1$A <- with(df, as.numeric(as.character(factor(stimulus,
       levels = c("S4", "S9", "S5", "S10"), c("1.1", "2.2", "3.2" , "5.8")))))

Or a better option may to do a join/merge with a key/value dataset

keydat <- data.frame(stimulus = c("S4", "S9", "S5", "S10"),
            A = c(1.1, 2.2, 3.2, 5.8))
df2 <- merge(df1, keydat, all.x = TRUE)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • hi, thank you for the solutions. Would I be able to assign specific values like `c (1.1,2.2,3.2,5.8)` and make them correspond to elements in column `stimulus`? – Kenny Feb 20 '21 at 19:17
  • @Shepard I updated the solution. Please check if that works. thanks – akrun Feb 20 '21 at 19:26