【发布时间】:2012-12-27 01:01:51
【问题描述】:
Stata 的inlist 允许我们引用变量的真实值或字符串值。我想知道R是否有这样的功能。
示例:
我想从变量state 中选择八个州(您可以将其视为state 在state 采用50 个字符串值(美国各州)的任何数据框中的列)。
inlist(state,"NC","AZ","TX","NY","MA","CA","NJ")
我想从变量 age 中选择九个年龄值(您可以将其视为 age 在任何数据框中的列 age 采用从 0 到 90 的数值)。
inlist(age,16, 24, 45, 54, 67,74, 78, 79, 85)
问题:
age<-c(0:10) # for this problem age takes values from 0 to 10 only
data<-as.data.frame(age) # age is a variable of data frame data
data$m<-ifelse(c(1,7,9)%in%data$age,0,1) # generate a variable m which takes value 0 if age is 1, 7, and 8 and 1, otherwise
Expected output:
age m
1 0 1
2 1 0
3 2 1
4 3 1
5 4 1
6 5 1
7 6 1
8 7 0
9 8 1
10 9 0
11 10 1
【问题讨论】:
-
我相信您可能正在寻找
match()或%in%,但对Stata 的inlist函数不太熟悉。 -
如果您定义了
state和age并显示了预期的输出,这将有所帮助... -
@Ananda 和@Ben:抱歉没有更明确。我现在已经编辑了这个问题,我希望它更清楚。
-
stata.com/help.cgi?inlist() 是更简洁直接的信息来源。在 Stata 中,
inlist()是一个函数,而不是一个命令。