本文介绍了从查找表创建一个新的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的数据集中有以下列:
I have the following columns in my data set:
presult aresult
I single
I double
I triple
I home run
SS strikeout
我要添加一个第三列依赖,这取决于列的结果值。
I would like to add a third column "bases" that is dependent upon the value of the result in column aresult.
例如,我希望基数为1单,2为双,3为三重,4为一个主场,0为一个出发。
For example, I would like bases to be 1 for a single, 2 for a double, 3 for a triple, 4 for a home run, and 0 for a strikeout.
通常我会创建一个新的变量,如下所示: / p>
Usually I would create the new variable like this:
dataset$base<-ifelse(dataset$aresult=="single", 1, 0)
问题是,我不知道如何编写新的变量而不将所有其他变量设置为零。
The problem is that I don't know how to code the new variable in without setting all other variables to zero.
推荐答案
定义查找表
lookup= data.frame(
base=c(0,1,2,3,4),
aresult=c("strikeout","single","double","triple","home run"))
然后使用join从plyr
then use join from plyr
dataset = join(dataset,lookup,by='aresult')
这篇关于从查找表创建一个新的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!