Leonhardt Guass
Leonhardt Guass

Reputation: 793

How to replace values in dataframe by id?

df <- data.frame(id = 1:10, key = 1:10)
replace_key <- c(2,5)
replace_id <- c(9,3)

I want to replace the key values into the values in replace_key by replace_id

required effect:

id key
1 1
2 2
3 5
4 4
5 5
6 6
7 7
8 8
9 2
10 10

Upvotes: 1

Views: 3026

Answers (4)

FinThusiast
FinThusiast

Reputation: 149

One can also do this operation using dplyr package.

df %>% mutate(key = replace(key, match(replace_id, id), replace_key))

Upvotes: 1

akrun
akrun

Reputation: 887173

Here is a join option with data.table

library(data.table)
setDT(df)[data.frame(id = replace_id, val= replace_key), key := as.integer(val), on = "id"]
df
#    id key
# 1:  1   1
# 2:  2   2
# 3:  3   5
# 4:  4   4
# 5:  5   5
# 6:  6   6
# 7:  7   7
# 8:  8   8
# 9:  9   2
#10: 10  10

Upvotes: 0

akuiper
akuiper

Reputation: 214967

Assuming you have unique ids, then you can use match to find out the row index where the keys need to be replaced and then assign the replace_key to these positions for the key column. Corresponding elements will be replaced in order:

df$key[match(replace_id, df$id)] <- replace_key

df
#   id key
#1   1   1
#2   2   2
#3   3   5
#4   4   4
#5   5   5
#6   6   6
#7   7   7
#8   8   8
#9   9   2
#10 10  10

Upvotes: 5

Ronak Shah
Ronak Shah

Reputation: 388982

We can use mapply over the two vectors replace_id and replace_key find the respective key and assign the respective values with <<-

mapply(function(x, y) df$key[df$id == x] <<- y, replace_id, replace_key)

df
#   id key
#1   1   1
#2   2   2
#3   3   5
#4   4   4
#5   5   5
#6   6   6
#7   7   7
#8   8   8
#9   9   2
#10 10  10

Upvotes: 1

Related Questions