我在替换数据帧中的值时遇到了一些问题.我想替换基于单独表格的值.下面是我试图做的一个例子.
我有一张桌子,每一行都是顾客,每一列都是他们购买的动物.我们把这个数据框称为table
.
> table
# P1 P2 P3
# 1 cat lizard parrot
# 2 lizard parrot cat
# 3 parrot cat lizard
我也有一个表,我会参考称为lookUp
.
> lookUp
# pet class
# 1 cat mammal
# 2 lizard reptile
# 3 parrot bird
我想做的是创建一个名为new
的新表,用一个函数将table
中的所有值替换为lookUp
中的class
列.我自己try 了lapply
个警告.
new <- as.data.frame(lapply(table, function(x) {
gsub('.*', lookUp[match(x, lookUp$pet) ,2], x)}), stringsAsFactors = FALSE)
Warning messages:
1: In gsub(".*", lookUp[match(x, lookUp$pet), 2], x) :
argument 'replacement' has length > 1 and only the first element will be used
2: In gsub(".*", lookUp[match(x, lookUp$pet), 2], x) :
argument 'replacement' has length > 1 and only the first element will be used
3: In gsub(".*", lookUp[match(x, lookUp$pet), 2], x) :
argument 'replacement' has length > 1 and only the first element will be used
有没有办法让这一切顺利进行?