基于查找表替換數(shù)據(jù)幀中的值在dataframe中,我在替換值時(shí)遇到了一些問(wèn)題。我想用一個(gè)單獨(dú)的表格來(lái)替換值。下面是我想要做的事情的一個(gè)例子。我有一張桌子,每一行都是顧客,每一欄都是他們買(mǎi)來(lái)的動(dòng)物。讓我們把這個(gè)叫做dataframetable.> table# P1 P2 P3# 1 cat lizard parrot# 2 lizard parrot cat# 3 parrot cat lizard我還有一個(gè)表,我將引用它,名為lookUp.> lookUp# pet class# 1 cat mammal# 2 lizard reptile# 3 parrot bird我要做的是創(chuàng)建一個(gè)名為new中的所有值都由一個(gè)函數(shù)替換table帶著class列l(wèi)ookUp..我自己用一個(gè)lapply函數(shù),但我收到了以下警告。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對(duì)如何使這件事奏效有什么想法嗎?
3 回答

幕布斯7119047
TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
你在問(wèn)題中貼出了一個(gè)不錯(cuò)的方法。這里有一個(gè)微笑的方法:
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)]
請(qǐng)注意,我使用空括號(hào)([])在這兩種情況下,保持new按原樣(數(shù)據(jù)幀)。
- 3 回答
- 0 關(guān)注
- 507 瀏覽
添加回答
舉報(bào)
0/150
提交
取消