如果你處理character
變量,而不是factors
,這將是一個更簡單的命題。
我將提供一個簡單的data.table
溶液(優雅和易於使用的語法以及許多其他優點)
x <- data.frame(c1=letters[1:26],c2=letters[26:1], stringsAsFactors =FALSE)
x[x$c1 == "m","c2"] <- NA
y <- data.frame(c1="m",c2="n", stringsAsFactors = FALSE)
library(data.table)
X <- as.data.table(x)
Y <- as.data.table(y)
用於合併的簡單起見,我將創建指示
X[,missing_c2 := is.na(c2)]
# a similar column in Y
Y[,missing_c2 := TRUE]
setkey(X, c2, missing_c2)
setkey(Y, c2, missing_c2)
# merge and replace (by reference) those values in X with the the values in `Y`
X[Y, c2 := i.c2]
列i.c2
意味着我們使用i
參數中的c2
的值到[
這種方法假設,如果c1 = 'm'
將在X
丟失並不是所有的值,你不想與'm'
其中c1='m'
替換c2
所有的值,只有那些缺少
底液
這是一個基本的解決方案 - 我使用合併,以便y
data.frame可以包含更多missing
替換比實際需要(即可能具有所有c1
值的值,但只需要c1=
m``。
# add a second missing value row because to make the solution more generalizable
x <- rbind(x, data.frame(c1 = 'm',c2 = NA, stringsAsFactors = FALSE))
missing <- x[is.na(x$c2),]
merged <- merge(missing, y, by = 'c1')
x[is.na(x$c2),] <- with(merged, data.frame(c1 = c1, c2 = c2.y, stringsAsFactors = FALSE))
如果您使用factors
,您會碰到一堵牆,確保水平相符。
在你的數據,並'y'只包含一個列,如例子?還是有其他無關數據?另外,我猜你可以在你的'x'數據框中有多個'NA'?他們總是在'$ c2'? –
這個例子很簡單,但在我的真實數據中有多行數據需要替換。 –