Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 209968

Replace values in a data.table based on row values in another table

$
0
0

I have two data.tables:

left_table <- data.table(a = c(1,2,3,4), b = c(4,5,6,7), c = c(8,9,10,11))

right_table <- data.table(record = sample(LETTERS, 9))

I would like to replace the numeric entries in left_table by the values associated with the corresponding row numbers in right_table. e.g. All instances of 4 in left_table are replaced by whatever letter (or set of characters in my real data) is on row 4 of right_table and so on.

I have this solution but I feel it's a bit cumbersome and a simpler solution must be possible?

right_table <- data.table(row_n = as.character(seq_along(1:9)), right_table)

for (i in seq_along(left_table)){
  cols <- colnames(left_table)
  current_col <- cols[i]

  # convert numbers to character to allow := to work for matching records
  left_table[,(current_col) := lapply(.SD, as.character), .SDcols = current_col]

  #right_table[,(current_col) := lapply(.SD, as.character), .SDcols = current_col]

  #set key for quick joins

  setkeyv(left_table, current_col)
  setkeyv(right_table, "row_n")

  # replace matching records
  left_table[right_table, (current_col) := record]
}

Viewing all articles
Browse latest Browse all 209968

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>