-1

I have a problem:

I shall add a new column in a data frame where any value of this new variable must be linked with a level of another variable.

For example: I would want to insert in this variable quote the value 800 for all rows with level's name M. Baldo of the variable location, and other values for the other three levels.

How can I do this? Thanks a lot

Vitali Avagyan
  • 1,193
  • 1
  • 7
  • 17
  • Ditto the duplication. Also, kindly provide a sample dataframe as it facilitates for the community to understand your problem. – JDG Sep 27 '19 at 15:17

1 Answers1

0

Although your dataset description leaves room for speculation, let us say you have the following structure:

dt = data.table(
  location = c('M. Baldo', 'Foo', 'Bar', 'Hello', 'World')
)

> dt
   location
1: M. Baldo
2:      Foo
3:      Bar
4:    Hello
5:    World

Say you want to create the column vQuote which takes the value 800 if location == 'M. Baldo' and 600 if location == 'Foo'. You can do the following using data.table:

locs = c('M. Baldo', 'Foo')    #Which location values?
corrval = c(800, 600)          #Which corresponding values in new column?

dt[, vQuote := sapply(location, function(x) corrval[which(locs == x)])]

> dt
   location vQuote
1: M. Baldo    800
2:      Foo    600
3:      Bar       
4:    Hello       
5:    World      

Obviously, vQuote is empty for rows [3:5] considering that they do not match any element in locs. You would have to specify your data structure more in depth. For instance, what value does vQuote take if no matches are in the set?

JDG
  • 1,342
  • 8
  • 18