如何通过R中的字典映射列 [英] How to map a column through a dictionary in R

查看:615
本文介绍了如何通过R中的字典映射列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有一个数据帧。该数据帧的一列取值为1到6.我有另一个映射该列的数据帧。有一些方法来替代这个列中的值而不使用循环(使用某些函数)?

  [,1] [, 2] 
[1,]1A
[2,]2B
[3,]3C
[4 ,]4D

[1] 4 2 2 3 4 1 4 4

存在一个返回下面的向量而不使用循环的函数?

  [1] DBBCDADD 


解决方案

您可以尝试




LETTERS [v1]
#[1]

  v1<  -  c(4,2,2,3,4,1,4,4) DBBCDADD


$ b $假设你的地图数据集第二列不只是LETTERS

  d1<  -  data.frame(Col1 = c(1,3,4,2),Col2 = c('j1','c9','19f','d18'),
stringsAsFactors = FALSE)

unname setNames(d1 [,2],d1 [,1])[as.character(v1)])
#[1]19fd18d18c919fj1 19f19f

  d1 $ Col2 [match(v1,d1 
#[1]19fd18d18c919fj119f19f


I have a data frame in R. One column of this data frame takes values from 1 to 6. I have another data frame that maps this column. There is some way to substitute the values in this column without using loops (using some function)?

     [,1] [,2]   
[1,] "1"  "A"
[2,] "2"  "B"
[3,] "3"  "C"
[4,] "4"  "D"

[1] 4 2 2 3 4 1 4 4

Exists a function that return the vector below without using loops?

[1] D B B C D A D D

解决方案

You can try

v1 <- c(4, 2, 2, 3, 4, 1, 4, 4)
LETTERS[v1]
#[1] "D" "B" "B" "C" "D" "A" "D" "D"

Suppose if your mapping dataset 2nd column is not just "LETTERS"

d1 <- data.frame(Col1=c(1,3,4,2), Col2=c('j1', 'c9', '19f', 'd18'),
                     stringsAsFactors=FALSE)

unname(setNames(d1[,2], d1[,1])[as.character(v1)])
#[1] "19f" "d18" "d18" "c9"  "19f" "j1"  "19f" "19f"

Or

d1$Col2[match(v1, d1$Col1)]
#[1] "19f" "d18" "d18" "c9"  "19f" "j1"  "19f" "19f"

这篇关于如何通过R中的字典映射列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆