将列中向量的给定索引替换为向量的值

Replace given index of a vector in a column by the values of the vector

提问人:TarJae 提问时间:11/18/2022 最后编辑:TarJae 更新时间:11/18/2022 访问量:44

问:

我正在为这个所谓的简单任务而苦苦挣扎:

更新了 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"  

我想将索引列 df$index 中的值替换为向量my_vector中相应索引的值

预期输出:

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

我尝试过许多变化,但没有结束。我也尝试过各种因素,但没有成功。whichmatch

r 索引替换 匹配

评论

3赞 Jilber Urbina 11/18/2022
检查您的数据样本,您的不是您的dputdata.frame
0赞 langtang 11/18/2022
df$index = my_vector[df$index]
0赞 TarJae 11/18/2022
已更新。感谢。

答:

3赞 langtang 11/18/2022 #1

您可以简单地按 中的值编制索引。my_vectordf$index

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")

评论

2赞 TarJae 11/18/2022
@thx。很尴尬,但有时我忍不住有这些差距。谢谢!
2赞 Ed_Gravy 11/18/2022
@TarJae,IMO毫无疑问是一个坏问题。像我这样的人也可以从你的帖子中学习:)