r从向量加入表列

发布于 2025-02-13 07:56:28 字数 465 浏览 3 评论 0原文

我想从另一列中的列中从表中获取向量的相应值。 (请看下面)

示例:

矢量:

v = c('A', 'B', 'C')

表:

# key     Value
 'C'        3
 'A'        1
 'B'        2

当我给予矢量va,b,c)时,我想以良好的顺序获得相应的值1,2,3

实际上,向量是数据集的Rownames,我需要用相应的值替换它。

我正在考虑从dplyr中使用left_join函数,但是我需要2个表。

感谢您的帮助

I would like to get the corresponding values of a vector in a table from a column in another column. (just look below)

example:

Vector:

v = c('A', 'B', 'C')

Table :

# key     Value
 'C'        3
 'A'        1
 'B'        2

When I give the vector v (A, B, C) I want to get back the corresponding values in the good order 1, 2, 3.

In reality, the vector is the rownames of a dataset, and I need to replace it with the corresponding values.

I was thinking about using the left_join function from Dplyr but I would need 2 tables for this.

Thanks for your help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怎樣才叫好 2025-02-20 07:56:28

基本r中的一种可能解决方案:

df$Value[match(v, df$key)]

#> [1] 1 2 3

使用dplyr

library(dplyr)

df %>% 
  mutate(x = Value[match(v, key)]) %>% 
  pull(x)

#> [1] 1 2 3

A possible solution in base R:

df$Value[match(v, df$key)]

#> [1] 1 2 3

Using dplyr:

library(dplyr)

df %>% 
  mutate(x = Value[match(v, key)]) %>% 
  pull(x)

#> [1] 1 2 3
终难遇 2025-02-20 07:56:28

首先,我投票决定删除 @akrun的答案。
第二是使用与组合 in%中的的替代方案:

which(v %in% df$key)

[1] 1 2 3

First of all I have voted to undelete @akrun's answer.
Second here is an alternative using which combined with %in%:

which(v %in% df$key)

[1] 1 2 3
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文