I suspect this will take member of the s-news community about two minutes to
solve, but I haven't been able to come up with an easy solution, and my
searchers of the archives haven't been succesful.
One of the nice things about ifelse is that it works on specific columns of
a dataframe. For example, in the syntax below I am able to turn values <3
into a 1 and all other values into a 5 for two of the three columns in the
data frame.
> TEMP<-data.frame(VAR1=rep(seq(1:5),2),VAR2=seq(1:10),VAR3=rep(seq(1:5),2))
> TEMP
VAR1 VAR2 VAR3
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 1 6 1
7 2 7 2
8 3 8 3
9 4 9 4
10 5 10 5
> TEMP[,c(1,3)]<-ifelse(TEMP[,c(1,3)]<3,1,5)
> TEMP
VAR1 VAR2 VAR3
1 1 1 1
2 1 2 1
3 5 3 5
4 5 4 5
5 5 5 5
6 1 6 1
7 1 7 1
8 5 8 5
9 5 9 5
10 5 10 5
While this works great, I haven't been able to a command that works the
same way if I don't have an "else". For instance, let's say that I only
want to change values <3 to 1, but I have no "else" component to alter. I
know that on a single vector, one can still use ifelse as in:
> TEMP<-data.frame(VAR1=rep(seq(1:5),2),VAR2=seq(1:10),VAR3=rep(seq(1:5),2))
> TEMP[,1]<-ifelse(TEMP[,1]<3,1,TEMP[,1])
> TEMP
VAR1 VAR2 VAR3
1 1 1 1
2 1 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 1 6 1
7 1 7 2
8 3 8 3
9 4 9 4
10 5 10 5
but what if I wanted to replace anything less than 3 with a 1 on multiple
columns in a data frame. The long-shot potential answer:
> TEMP[,c(1,3)]<-ifelse(TEMP[,c(1,3)]<3,1,TEMP[,c(1,3)])
does not work....
Thanks,
Paul
|