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
答案 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_id
和replace_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