Reputation: 5779
I am getting familiar with R after a good amount of experience with SAS and I've quickly discovered that functions in R do NOT behave like macros in SAS, so I need a little guidance.
Here is my function that doesn't work:
dscore<-function(data,var){
ave<-mean(data$var)
sd<-sd(data$var)
data$vardscore<-(data$var-ave)/sd
return(data)
}
I am using the cars dataset
cars<-dscore(cars,speed)
Should give me back the cars dataframe with an additional column that is the Cohen D value for the speed variable for that observation.
I get all sorts of crazy errors, so I would appreciate any help.
edit:
dbind<-function(data,var){
var<-substitute(var)
var<-as.character(var)
ave<-mean(data[,var])
sd<-sd(data[,var])
name<-paste0(var,"dscore")
data$name=((data[,var]-ave)/sd)
return(data)
}
I need help dynamically naming the new column based on the input. Right now I just get a new column named "name"
Upvotes: 3
Views: 3471
Reputation: 18580
You cannot use the $
sign with a variable. Try instead:
data[,var]
where var
must be a character, e.g. "speed"
dscore<-function(data,var){
ave<-mean(data[,var])
sd<-sd(data[,var])
data[,paste0(var,"dscore")]<-(data[,var]-ave)/sd
return(data)
}
cars<-dscore(cars,var="speed")
Upvotes: 4
Reputation: 452
dscore<-function(data,var){
ave<-mean(data[,var])
sd<-sd(data[,var])
data$vardscore<-(data[,var]-ave)/sd
return(data)
}
cars<-dscore(cars, "speed")
Upvotes: 3