Reputation: 1480
I have a data frame
x<-c(1,3,0,2,4,5,0,-2,-5,1,0)
y<-c(-1,-2,0,3,4,5,1,8,1,0,2)
data.frame(x,y)
x y
1 1 -1
2 3 -2
3 0 0
4 2 3
5 4 4
6 5 5
7 0 1
8 -2 8
9 -5 1
10 1 0
11 0 2
I would like to replace the data in column y with data from column x and also replacing in y the instances that where <0 in y and replacing them by 0. This will result in the following data frame
data.frame(x,y)
x y
1 1 0
2 3 0
3 0 0
4 2 2
5 4 4
6 5 5
7 0 0
8 -2 -2
9 -5 -5
10 1 0
11 0 0
Thanks
Upvotes: 0
Views: 66
Reputation: 124646
Given your x
and y
vectors, create the data.frame
in one swift move:
> data.frame(x, y=ifelse(y < 0, 0, x))
x y
1 1 0
2 3 0
3 0 0
4 2 2
5 4 4
6 5 5
7 0 0
8 -2 -2
9 -5 -5
10 1 1
11 0 0
Upvotes: 1
Reputation: 6534
In one line:
> df <- transform(data.frame(x,y), y = ifelse(y<0,0,x))
> df
x y
1 1 0
2 3 0
3 0 0
4 2 2
5 4 4
6 5 5
7 0 0
8 -2 -2
9 -5 -5
10 1 1
11 0 0
Note that the resulting data differs from the reference result you provide on record 10. I suspect that this might be because you applied the condition <= 0 rather than < 0? Otherwise the 1 would be carried across from the x field for this record.
Upvotes: 1
Reputation: 54237
x<-c(1,3,0,2,4,5,0,-2,-5,1,0)
y<-c(-1,-2,0,3,4,5,1,8,1,0,2)
df <- data.frame(x, y)
df$y <- ifelse(y<0,0,x)
df
# x y
# 1 1 0
# 2 3 0
# 3 0 0
# 4 2 2
# 5 4 4
# 6 5 5
# 7 0 0
# 8 -2 -2
# 9 -5 -5
# 10 1 1
# 11 0 0
Upvotes: 2