首页 > 解决方案 > 在数据表 R 中,如何创建一个新变量,该变量为特定观察值取特定值?

问题描述

在数据表中,我试图创建一个在满足某个观察值时取值的变量。

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”。

标签: r

解决方案


如果数据以数据框的形式出现,那就直截了当:

#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

推荐阅读