Olga Lyashevska
2010-Sep-01 14:35 UTC
[R] standardize columns selectively within a dataframe
Dear all, I have a dataframe: df<-dataframe(a=c(1,2,3),b=c(4,5,6),c=c(7,8,9),d=c(10,11,12)) I want to obtain a new dataframe with columns a and b being standardized ((x-mean(x))/sd(x)); the other two columns (c,d) I want to leave unchanged. What is the best way to achieve this? I have been trying to use subscripts but did not succeed so far. Any tips? Many thanks, Olga
David Winsemius
2010-Sep-01 14:42 UTC
[R] standardize columns selectively within a dataframe
On Sep 1, 2010, at 10:35 AM, Olga Lyashevska wrote:> Dear all, > > I have a dataframe: > df<-dataframe(a=c(1,2,3),b=c(4,5,6),c=c(7,8,9),d=c(10,11,12)) > > I want to obtain a new dataframe with columns a and b being > standardized > ((x-mean(x))/sd(x)); the other two columns (c,d) I want to leave > unchanged. What is the best way to achieve this? I have been trying to > use subscripts but did not succeed so far.> df[ , 1:2] <- scale(df[ , 1:2]) > df a b c d 1 -1 -1 7 10 2 0 0 8 11 3 1 1 9 12 -- David Winsemius, MD West Hartford, CT
Adaikalavan Ramasamy
2010-Sep-01 14:44 UTC
[R] standardize columns selectively within a dataframe
If you want to scale within columns, you could try
cbind( scale(df[,1:2]), df[ ,-c(1:2)] )
a b c d
1 -1 -1 7 10
2 0 0 8 11
3 1 1 9 12
and it is data.frame() btw.
On 01/09/2010 15:35, Olga Lyashevska wrote:> Dear all,
>
> I have a dataframe:
> df<-dataframe(a=c(1,2,3),b=c(4,5,6),c=c(7,8,9),d=c(10,11,12))
>
> I want to obtain a new dataframe with columns a and b being standardized
> ((x-mean(x))/sd(x)); the other two columns (c,d) I want to leave
> unchanged. What is the best way to achieve this? I have been trying to
> use subscripts but did not succeed so far.
>
> Any tips?
>
> Many thanks,
> Olga
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.