You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用向量对应索引值替换DataFrame中index列的内容?

解决方法

直接利用向量的索引特性就能完成替换,不需要复杂的函数:

# 替换index列
df$index <- my_vector[df$index]

运行上述代码后,查看数据框就能得到预期结果:

> df
     Species index
1     setosa  four
2 not_setosa three
3     setosa   two
4     setosa  five
5     setosa   one
6     setosa three

原理说明

my_vector的索引位置和df$index中的数值完全对应:比如df$index里的4对应my_vector[4](即"four"),1对应my_vector[1](即"one"),直接通过索引取值就能完成批量替换,比用which或match更简洁直接。

内容的提问来源于stack exchange,提问作者TarJae

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 23:35:23