我正在嘗試將從圖表審查中收集的新資料添加到我的資料庫中,但似乎無法到達那里。
我嘗試撰寫一個新變數,然后使用邏輯函式來選擇要使用的資料點,但是使用整個變數不起作用,因為它是一個向量而不是單個資料點。如何對其進行編程以使用來自相同觀察但不同變數的資料點?
mydf <- structure(list(Year = c(2014L, 2014L, 2015L, 2015L, 2016L),
Var1 = c(15, 12, 2, 16, NA),
Var2 = c(15, 13, 104, NA, NA),
Agree = c(1, 0, 0, 1, 1)),
.Names = c("Year", "Var1", "Var2", "Agree"),
row.names = c(NA, 5L), class = "data.frame")
## mydf
# Year Var1 Var2 Agree
# 1 2014 15 15 1
# 2 2014 13 12 0
# 3 2015 2 104 0
# 4 2015 16 NA 1
# 5 2016 NA NA 1
mydf$true <- if_else(mydf$Agree == 1, mydf$Var1, mydf$Var2)
## Error Message
# Error: `true` must be length 0 (length of `condition`) or one, not 5.
# Run `rlang::last_error()` to see where the error occurred.
## What I want
# Year Var1 Var2 Agree True
# 1 2014 15 15 1 15
# 2 2014 13 12 0 12
# 3 2015 2 104 0 104
# 4 2015 16 NA 1 16
# 5 2016 NA NA 1 NA
有任何想法嗎?
uj5u.com熱心網友回復:
我不確定您最初擁有哪些軟體包。我是這樣做的,得到了??你需要的答案:
mydf <- structure(list(Year = c(2014L, 2014L, 2015L, 2015L, 2016L),
Var1 = c(15, 12, 2, 16, NA),
Var2 = c(15, 13, 104, NA, NA),
Agree = c(1, 0, 0, 1, 1)),
.Names = c("Year", "Var1", "Var2", "Agree"),
row.names = c(NA, 5L), class = "data.frame")
library(dplyr)
mydf$true <- if_else(mydf$Agree == 1, mydf$Var1, mydf$Var2)
uj5u.com熱心網友回復:
正如@Ma?l指出的那樣,您可能使用 if_else 函式加載了多個包。要修復此錯誤,您可以指定要使用的包。
library(dplyr)
mydf$true <- dplyr::if_else(mydf$Agree == 1, mydf$Var1, mydf$Var2)
一個小的補充,從長遠來看對你使用 R 有幫助,我建議你處理dplyr和mutate。檢查以下代碼作為上述問題的示例:
mydf %>%
mutate(true = ifelse(mydf$Agree == 1, mydf$Var1, mydf$Var2))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/375192.html
上一篇:使用r中長格式data.table中的兩個變數按條件改變變數
下一篇:在R中合并多對資料幀
