簡體   English   中英

在數據表 R 中,如何創建一個新變量,該變量為特定觀察值取特定值?

[英]In data table, R, how do I make a new variable that takes a certain value for specific observations?

在數據表中,我試圖創建一個在滿足某個觀察值時取值的變量。

smoked <- matrix(c("A","A","A","B","B","B","A","B","A"),ncol=3,byrow=TRUE)
colnames(smoked) <- c("Type","Name","cusip")
rownames(smoked) <- c("A","B","C")
smoked <- as.table(smoked)
smoked

我將如何創建另一個列,該列在每次在“名稱”列中滿足條件時都響應“B”。然后在每次不滿足的情況下都響應“非 B”。

嘗試將cbind()ifelse() function 一起使用。

smoked <- matrix(c("A","A","A","B","B","B","A","B","A"),ncol=3,byrow=TRUE)
colnames(smoked) <- c("Type","Name","cusip")
rownames(smoked) <- c("A","B","C")
smoked <- as.table(smoked)

# use cbind
smokedNew <- cbind(smoked, newCol = ifelse(test = smoked[,"Name"] == "B", yes = "B", no = "not B"))

smokedNew

#   Type Name cusip newCol 
# A "A"  "A"  "A"   "not B"
# B "B"  "B"  "B"   "B"    
# C "A"  "B"  "A"   "B"  

如果數據以數據框的形式出現,那就直截了當:

#create data frame
smoked <- data.frame( Type=c("A","B","A"), Name=c("A","B","B"), cusip=c("A","B","A"))

# test function
my.test <- function(test.value, test.on) { paste0(ifelse(test.value==test.on,'','not '), test.on) }

# now testing on content of Name colum
smoked$res1 <- sapply( smoked$Name, FUN=my.test, test.on='B' )
smoked$res2 <- sapply( smoked$Name, FUN=my.test, test.on='C' )

產生:

> print(smoked)
  Type Name cusip  res1  res2
1    A    A     A not B not C
2    B    B     B     B not C
3    A    B     A     B not C

暫無
暫無

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

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