【问题标题】:Need to create a dummy variable in R that is equal to 1 if the variable name contains specific phrases如果变量名称包含特定短语,则需要在 R 中创建一个等于 1 的虚拟变量
【发布时间】:2017-10-08 16:50:40
【问题描述】:

我想创建一个新变量 created_idx_var,如果变量名称包含任何短语“idx”、“Idx”、“indx”、“Indx”、“index”、“Index”,则该变量等于 1 、“etf”、“ETF”,或者如果变量索引等于“是”。

我刚开始学习 R。我的第一步是消除数据集,只保留股票基金。然后我想创建一个标志来查看基金是否是指数基金。我在网上搜索,但没有找到任何东西。

部分样本数据: enter image description here

这是我目前的代码。

library(readxl)
mydata <- read_excel("C:/category.xlsx",sheet = 1)
utils::View(mydata)
mydata <- subset(mydata, global_group=="Equity")

【问题讨论】:

  • 你能分享一些代码(甚至是不起作用的代码),以便更容易想象你在做什么吗?
  • 请提供一个最小的、可重现的例子。参考here
  • 请看%in%
  • @Hayley Han,您应该提供来自 C:/category.xlsx 文件的数据样本。

标签: r dummy-variable


【解决方案1】:

假设你有一个值向量:

x = c("idx", "a", "b","c", "Index")

然后你可以创建一个你提到的二进制向量,如果匹配列表中的任何字符串(idx|Idx|indx|Indx|index|Index|etf|ETF)0,则具有1,否则:

result = sapply(x, function(x) ifelse(grepl("idx|Idx|indx|Indx|index|Index|etf|ETF", x) == 1, 1, 0))

【讨论】:

  • 不需要ifelse()。你可以简单地做+sapply(x, function(x) grepl("idx|Idx|indx|Indx|index|Index|etf|ETF", x))+stringi::stri_detect_regex(x, "idx|Idx|indx|Indx|index|Index|etf|ETF")
猜你喜欢
  • 2021-06-27
  • 2018-09-08
  • 1970-01-01
  • 1970-01-01
  • 2023-01-18
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多