我正在努力完成这项理应很简单的任务:

updated df:个 我有这个数据框:

df<- structure(list(Species = c("setosa", "not_setosa", "setosa", 
"setosa", "setosa", "setosa"), index = c(4L, 3L, 2L, 5L, 1L, 
3L)), class = "data.frame", row.names = c("1", "2", "3", "4", 
"5", "6"))

     Species index
1     setosa     4
2 not_setosa     3
3     setosa     2
4     setosa     5
5     setosa     1
6     setosa     3

这个向量是:

my_vector <- c("one", "two", "three", "four", "five", "six")

[1] "one"   "two"   "three" "four"  "five"  "six"  

一百零二

预期输出:

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

我try 了whichmatch的许多变化,但没有结束.我也try 了一些因素,但没有成功.

推荐答案

您可以简单地通过df$index中的值来索引my_vector.

df$index = my_vector[df$index]

输出:

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

输入:

structure(list(Species = c("setosa", "not_setosa", "setosa", 
"setosa", "setosa", "setosa"), index = c("four", "three", "two", 
"five", "one", "three")), row.names = c(NA, -6L), class = "data.frame")

R相关问答推荐

R -模运算后的加法

如果行和列名以相同的开头,将矩阵值设置为0

R Lubridate:舍入/快照日期时间到一天中最近的任意时间?

R创建一个数据透视表,计算多个组的百分比

如果行和大于值,则过滤

selectInput不返回ALL,并将因子转换为shiny 的数字

如果第一个列表中的元素等于第二个列表的元素,则替换为第三个列表的元素

如何自定义3D散点图的图例顺序?

IMF IFS数据以R表示

如何在R forestplot中为多条垂直线分配唯一的 colored颜色 ?

2个Rscript.exe可执行文件有什么区别?

如何将R中数据帧中的任何Nas替换为最后4个值

R中边际效应包中Logistic回归的交互作用风险比

列名具有特殊字符时的循环回归

扩展R中包含列表的数据框

计算Mean by分组和绑定到R中的数据集

以任意顺序提取具有多个可能匹配项的组匹配项

整理ggmosaic图的标签

如果满足条件,则替换列的前一个值和后续值

使用nls()函数的非线性模型的半正态图