gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:16:47 26 4
gpt4 key购买 nike

我正在努力完成这个看似简单的任务:

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

我想用向量 my_vector 中相应索引的值替换索引列 df$index 中的值/p>

预期输出:

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

我已经尝试了很多 whichmatch 的变体,但没有结束。我也尝试了因素,但没有成功。

最佳答案

您可以简单地通过 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")

关于用向量的值替换列中向量的给定索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74479338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com