[英]In data table, R, how do I make a new variable that takes a certain value for specific observations?
In data table, i am trying to make a variable that takes a value when a certain observation has been met.在数据表中,我试图创建一个在满足某个观察值时取值的变量。
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
How would i create a another column that that responds "B" every occasion the condition is met within the "name" columnn.. and then "not B" for every occasion it does not.我将如何创建另一个列,该列在每次在“名称”列中满足条件时都响应“B”。然后在每次不满足的情况下都响应“非 B”。
Try using cbind()
with the ifelse()
function.尝试将
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"
If the data comes as data frame, it is straight forward:如果数据以数据框的形式出现,那就直截了当:
#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' )
which yields:产生:
> 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.