为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

凤凰求蛊 2019-07-20 14:27:51
基于查找表替换数据帧中的值在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带着class列lookUp..我自己用一个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对如何使这件事奏效有什么想法吗?
查看完整描述

3 回答

?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

你在问题中贴出了一个不错的方法。这里有一个微笑的方法:


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 <- df

new[] <- look$class[match(unlist(df), look$pet)]

请注意,我使用空括号([])在这两种情况下,保持new按原样(数据帧)。

查看完整回答
反对 回复 2019-07-20
  • 3 回答
  • 0 关注
  • 440 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信