簡體   English   中英

用雙重條件替換R中的數據幀值

[英]replace data frame values in R with double conditions

我有這個數據框:

 A  B     C      D
 1  cola  light  0
 2  cola  light  0
 3  cola  lemon  0
 4  Pepsi lemon  0
 5  Pepsi lemon  0

我想對“ B”和“ C”做一個雙重條件,並將結果放在D中,例如(偽代碼):

 if B=="cola" and C=="light"
  D=10 else D=20

在RI中,ifelse做到了,但是我的問題是B =“ Cola”或c =“ light”始終為FALSE,我是Java用戶,比較字符串或字符更容易,我使用(等於或compareTo)。 但是在R中,我不知道如何處理此類問題,我嘗試按as.character對其進行轉換,但沒有結果。 我的狀況仍然重新調整為False。

謝謝您的幫助

要么

 dat$D <- c(20,10)[(dat$B=="cola" & dat$C=="light")+1]
dat$D
#[1] 10 10 20 20 20

數據

dat <- structure(list(A = 1:5, B = c("cola", "cola", "cola", "Pepsi", 
"Pepsi"), C = c("light", "light", "lemon", "lemon", "lemon"), 
D = c(0L, 0L, 0L, 0L, 0L)), .Names = c("A", "B", "C", "D"
), class = "data.frame", row.names = c(NA, -5L))

更新資料

如果您的數據集列為:

 dat$B <- c( " cola ", " cola", "cola ", "Pepsi", "Pepsi")
 c(20,10)[(dat$B=="cola" & dat$C=="light")+1]
 #[1] 20 20 20 20 20

在這種情況下,

  c(20,10)[(grepl("cola", dat$B)&grepl("light", dat$C)) +1]
 #[1] 10 10 20 20 20

或者您可以使用str_trim

library(stringr)

dat[,2:3] <- lapply(dat[,2:3], str_trim) 
c(20,10)[(dat$B=="cola" & dat$C=="light")+1]
 #[1] 10 10 20 20 20

這應該工作:

df$D <- ifelse(df$B == "cola" & df$C == "light", 10, 20)
A <- 1:5
B <- c(rep("cola",3), rep("Pepsi", 2))
C <- c(rep("light",2), rep("lemon", 3))
D <- rep(0,5)

然后我有完全像你的data.frame

> data
  A     B     C D
1 1  cola light 0
2 2  cola light 0
3 3  cola lemon 0
4 4 Pepsi lemon 0
5 5 Pepsi lemon 0

根據@ zx8754

> data$D <- ifelse(data$B=="cola" & data$C=="light", 10,20)
> data
  A     B     C  D
1 1  cola light 10
2 2  cola light 10
3 3  cola lemon 20
4 4 Pepsi lemon 20
5 5 Pepsi lemon 20

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM