我在R中有一个具有x和y值的数据帧。 x中有NA值,我想根据y值填充特定的字符串。
示例数据框:
df1 = data.frame(x = c("Canada", "United States", NA, NA, NA),
y = c("CAN", "USA", "TWN", "TWN", "ARG"))
预期结果:
df2 = data.frame(x = c("Canada", "United States", "Taiwan", "Taiwan", NA),
y = c("CAN", "USA", "TWN", "TWN", "ARG"))
我尝试过
df2 <- df1 %>% transform(df1, x = ifelse(y == "TWN", "Taiwan", x))
但是对于所有其他不包含“ TWN”的观测,这将删除所有x和y值。我在这里找到的大多数其他示例都在替换所有NA值,而且我似乎无法弄清楚如何有条件地对另一列中的字符串执行此操作。这将需要处理非常大的数据帧,因此效率是理想的。
答案 0 :(得分:1)
我认为,一种更好的方法是维护一个数据框,其中包含您要使用的所有密钥和替换项,如果缺少完整的国家/地区名称,
df1 <- data.frame(x=c("Canada", "United States", NA, NA, NA),
y=c("CAN", "USA", "TWN", "TWN", "ARG"), stringsAsFactors=FALSE)
df2 <- data.frame(y=c("TWN", "ARG"), value=c("Taiwan", "Argentina"),
stringsAsFactors=FALSE)
result <- merge(df1, df2, by="y", all=TRUE)
result$x <- ifelse(is.na(result$x), result$value, result$x)
result <- result[, c("y", "x")]
result
y x
1 ARG Argentina
2 CAN Canada
3 TWN Taiwan
4 TWN Taiwan
5 USA United States
答案 1 :(得分:0)
在使用“ [”时,首先需要增加因子列的级别,并为“ x”为NA和“ y”为TWN的联合条件建立逻辑索引。
> levels(df1$x) <- c(levels(df1$x), 'Taiwan')
> df1[is.na(df1$x) & df1$y=='TWN', 'x'] <- 'Taiwan'
> df1
x y
1 Canada CAN
2 United States USA
3 Taiwan TWN
4 Taiwan TWN
5 <NA> ARG
答案 2 :(得分:0)
最简单的方法是在R中使用data.table库
library(data.table)
setDT(df1)
df1[y=="TWN",x:="TAIWAN"]
应该像专业人士一样工作。
答案 3 :(得分:0)
我喜欢使用lookUpTable(named character
)解决这些问题。
lookUpTable = c("Canada", "United States", "Taiwan", "Argentina")
names(lookUpTable) = c("CAN", "USA", "TWN", "ARG")
# CAN USA TWN ARG
#"Canada" "United States" "Taiwan" "Argentina"
df1$x <- lookUpTable[df1$y]
# x y
#1 United States CAN
#2 Argentina USA
#3 Taiwan TWN
#4 Taiwan TWN
#5 Canada ARG
数据:
df1 = data.frame(x = c("Canada", "United States", NA, NA, NA),
y = c("CAN", "USA", "TWN", "TWN", "ARG"))