I have a data frame (df) with variables such as CA, VT, NC, AZ, CAvalue, VTvalue, NCvalue, AZvalue etc.
In Stata, I can use the foreach
command and generate
new variables:
foreach x in CA VT NC AZ {
gen `x'1 = 0
replace `x'1 = 1 if `x'value > 1
}
When I convert this code to R , I found it problematic.
Here's what I wrote:
x=c("CA","VT","NC","AZ")
x_1=paste(x,"1",sep="")
m1=as.data.frame(matrix(0,ncol=length(x),nrow=NROW(df)))
colnames(m1)=x_1
While I have no problem in creating the new variables ending with "1", I don't know how to convert the line starting with "replace". I tried to create another vector with CAtime, VTtime, NCtime, and AZtime. But I don't know how to incorporate them into the loop without writing it four times.
UPDATE: Originally, my data looks something like this:
df=as.data.frame(matrix(runif(200,1,150),ncol=8,nrow=25))
name=c("CA","VT","NC","AZ","CAtime","VTtime", "NCtime","AZtime")
colnames(df)=name
Then I want to create 4 new variables CA1, VT1, NC1, AZ1,in a new data frame m1:
x=c("CA","VT","NC","AZ")
x_1=paste(x,"1",sep="")
m1=as.data.frame(matrix(0,ncol=length(x),nrow=NROW(df)))
colnames(m1)=x_1
All the values of variables in m1=0.
Then, if CAtime>1, I want the corresponding cell in CA1=1. That applies for all the four variables CAtime, VTtime, NCtime, AZtime. I don't want to write four loops and that's why I am stuck.
=exp required r(100);
but maybe because I am running it on linux. – Sigmatismgenerate `x'1 = `x'value > 1
is a cleaner replacement for your two commands within the loop. – Valentine