r - 根据命名向量改变列,如查找表

标签 r

blah <- data.frame(
  x = 1:3,
  y = rnorm(3)
)

named_vect <- 1:3
names(named_vect) <- c('blah', 'dog', 'cat')

我想根据变量 x 的值创建一个新列,其中 x 中的数字对应于 named_vect 中相应数字的名称。

blah <- blah %>% 
  mutate(text_name = ???)

期望的输出:

  x          y text_name
1 1 -0.2390928      blah
2 2 -0.8818895       dog
3 3  0.1537032       cat

最佳答案

如果我们反转'named_vect'的名称,值,我们可以使用recode

library(dplyr)
named_vect <- setNames(names(named_vect), named_vect)
blah %>% 
    mutate(text_name = recode(x, !!! named_vect))

-输出

#  x          y text_name
#1 1 -2.0009292      blah
#2 2  0.3337772       dog
#3 3  1.1713251       cat

或者使用 base R,我们通过转换为 character 来匹配 'x' 以匹配 'named_vect' 的名称

blah$text_name <- named_vect[as.character(blah$x)]

关于r - 根据命名向量改变列,如查找表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65330867/

相关文章:

R数据表: use function on group except current row

r - 在没有 ggplot 的情况下计算 probability_trans(distribution ="norm")

r - data.table替代管道

r - 将矩阵转换为R中的栅格

在 Google Drive 上的 R 项目中打开时,Rmarkdown 无法渲染内联绘图

r - R : How to customize the coloring of clusters?的传单

r - 如何为r中ROC曲线下面积的加权平均值创建置信区间?

r - 在 R 中进行模糊匹配的更有效方法?

r - 从 R 中的多个列表对象中提取相同字段的值

r - R中的全局变量和列表赋值,得到意想不到的结果