如何用id替换dataframe中的值?

时间:2016-12-27 04:01:05

标签: r

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

我想通过replace_id

将键值替换为replace_key中的值

要求的效果:

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

4 个答案:

答案 0 :(得分:3)

假设您有唯一的ID,那么您可以使用>>> import pocketsphinx Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> import pocketsphinx File "C:\Python27\lib\site-packages\pocketsphinx\__init__.py", line 35, in <module> from sphinxbase import * File "C:\Python27\lib\site-packages\sphinxbase\__init__.py", line 32, in <module> from .ad import * File "C:\Python27\lib\site-packages\sphinxbase\ad.py", line 35, in <module> _ad = swig_import_helper() File "C:\Python27\lib\site-packages\sphinxbase\ad.py", line 34, in swig_import_helper return importlib.import_module('_ad') File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: No module named _ad >>> import sphinxbase Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> import sphinxbase File "C:\Python27\lib\site-packages\sphinxbase\__init__.py", line 32, in <module> from .ad import * File "C:\Python27\lib\site-packages\sphinxbase\ad.py", line 35, in <module> _ad = swig_import_helper() File "C:\Python27\lib\site-packages\sphinxbase\ad.py", line 34, in swig_import_helper return importlib.import_module('_ad') File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: No module named _ad 找出需要替换密钥的行索引,然后将match分配给replace_key的这些位置柱。相应的元素将按顺序替换:

key

答案 1 :(得分:1)

我们可以使用mapply对两个向量replace_idreplace_key找到相应的键,并使用<<-分配相应的值

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

答案 2 :(得分:1)

也可以使用dplyr软件包执行此操作。

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

答案 3 :(得分:0)

以下是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