gpt4 book ai didi

r - 我正在比较两列以创建第三列...它不起作用?

转载 作者:行者123 更新时间:2023-12-02 01:39:00 27 4
gpt4 key购买 nike

这绝对是一个新手问题,但我被卡住了,无法在网上找到类似的帮助。我正在尝试比较数据框的两列以创建第三列。这是我想比较 Distx 和 Disty 的 mydf。如果其中任何一个都有值,我想保留它并将其放在新的 Distz 列中。如果它们都是“Missing”,我想将“Missing”放在 Distz 中。以下是我想要获取的数据框。

    ID <- c(1, 2, 3, 4, 5, 6)
Distx <- c("A", "B", "Missing", "Missing", "G", "Missing")
Disty <- c("Missing", "Missing", "C", "Missing", "Missing", "E")

mydf <- data.frame(ID, Distx, Disty, Distz)
mydf

ID Distx Disty Distz
1 1 A Missing A
2 2 B Missing B
3 3 Missing C C
4 4 Missing Missing Missing
5 5 G Missing G
6 6 Missing E E

这是不起作用的代码...起初我以为我没有正确索引,但是下面的第二次代码尝试结果相同..没有错误消息但结果是 1,而不是列的实际值....?

    for (i in seq(1:nrow(mydf))){
if (mydf$Distx[i] == "Missing" && mydf$Disty[i] != "Missing"){
mydf$Distz[i]<- mydf$Disty[i]}
if (mydf$Distx[i] != "Missing" && mydf$Disty[i] == "Missing"){
mydf$Distz[i]<- mydf$Distx[i]}
if (mydf$Distx[i] == "Missing" && mydf$Disty[i] == "Missing"){
mydf$Distz[i]<- "Missing"}
}

#for the purposes of readability I only ran two of the tests in this code
within(mydf, {
Distz <- ifelse(Distx == "Missing" & Disty != "Missing", Disty, ifelse(Distx != "Missing" & Disty == "Missing", Distx))
})

#Both results look like this ...???

ID Distx Disty Distz
1 1 A Missing 1
2 2 B Missing 1
3 3 Missing C 1
4 4 Missing Missing 1
5 5 G Missing 1
6 6 Missing E 1

在此先感谢您的帮助

最佳答案

您可以尝试嵌套的 ifelse 语句:

mydf$Distz <- with(mydf, ifelse(Distx == "Missing" & Disty == "Missing", "Missing", 
ifelse(Distx != "Missing", as.character(Distx),
ifelse(Disty != "Missing", as.character(Disty), NA))))
mydf
# ID Distx Disty Distz
# 1 1 A Missing A
# 2 2 B Missing B
# 3 3 Missing C C
# 4 4 Missing Missing Missing
# 5 5 G Missing G
# 6 6 Missing E E

您在代码中遇到的问题是您的变量是“因子”类,而不是“字符”类,因此代码记录的是因子“水平”而不是因子标签。这在上面通过使用 as.character() 将因子强制转换为字符来解决。

关于r - 我正在比较两列以创建第三列...它不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29500739/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com