r - 在数据表 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”。
解决方案
如果数据以数据框的形式出现,那就直截了当:
#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
推荐阅读
- javascript - 如何使用 chrome 开发工具获取 youtube 成绩单 url?
- xsd - xsd复杂类型继承中的限制问题
- python - 尝试使用 Anaconda-navigator 安装 Tensorflow,但在导航器中找不到包
- flutter - 发射状态更改后保持 UI Cubit Flutter
- python - 合并日期时间和范围的数据框
- php - 在 apache2 启动时启动 php 脚本
- snowflake-cloud-data-platform - Infromatica 云 - 由于以下错误,Snowflake 连接器无法从源读取数据:null
- c# - 当 .csproj 被称为 Nuget 包时出现 FileNotFoundException
- javascript - 使用虚拟主机服务器从网站发送电子邮件
- amazon-fire-tv - 为什么我在 FireTV 4K 上设置代理时卡在登录页面