在R中使用键的变量标签?

时间:2014-09-23 19:39:27

标签: r

让我们说我将一个csv导入R中它看起来像这样。

1 4 3 5
9 6 2 6 

我还有另一个类似

的csv
1 apple
2 banana
3 toast
4 beer
5 chips
6 cheese
9 wine

有没有办法使用第二个标记第一个中的值?我希望这是有道理的。

1 个答案:

答案 0 :(得分:3)

这是一种可行的方法:

# recreate your input data
vals <- read.table(
text=
"1 4 3 5
9 6 2 6")

map <- read.table(
text=
"1 apple
2 banana
3 toast
4 beer
5 chips
6 cheese
9 wine",stringsAsFactors=F)
names(map) <- c('K','V')


# - turn vals into a vector (using unlist function)
# - get the row indexes of the unlisted keys corresponding 
#   to map keys (using match function)
# - using the indexes select the key names in map (using vector subsetting [])
# - turn the character vector into 2d matrix with original dimension of vals
# - coerce to data.frame
mapped <- as.data.frame(matrix(map$V[match(unlist(vals),map$K)],nrow=nrow(vals)))

# > mapped
# V1     V2     V3     V4
# 1 apple   beer  toast  chips
# 2  wine cheese banana cheese