基于查找表替换数据帧中的值

基于查找表替换数据帧中的值

在dataframe中,我在替换值时遇到了一些问题。我想用一个单独的表格来替换值。下面是我想要做的事情的一个例子。

我有一张桌子,每一行都是顾客,每一栏都是他们买来的动物。让我们把这个叫做dataframetable.

> 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带着classlookUp..我自己用一个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 used2: In gsub(".*", lookUp[match(x, lookUp$pet), 2], x) :
  argument 'replacement' has length > 1 and only the first element will be used3: In gsub(".*", lookUp[match(x, lookUp$pet), 2], x) :
  argument 'replacement' has length > 1 and only the first element will be used

对如何使这件事奏效有什么想法吗?


凤凰求蛊
浏览 447回答 3
3回答

幕布斯7119047

你在问题中贴出了一个不错的方法。这里有一个微笑的方法:new <- df  # create a copy of df# using lapply, loop over columns and match values to the look up table. store in "new".new[] <- lapply(df, function(x) look$class[match(x, look$pet)])另一种更快的办法是:new <- dfnew[] <- look$class[match(unlist(df), look$pet)]请注意,我使用空括号([])在这两种情况下,保持new按原样(数据帧)。
打开App,查看更多内容
随时随地看视频慕课网APP