Reputation:
I have data.frame object that consist of two vectors v1, v2. As you can see from my data, v1 contains 0e+00, I want to assign this values to the row that contains 0e+00. I attempted to do this but I did not get what I expected. How can do this in R? However, this is my attempt to do this, but it won't work:
res<- apply(data, 1, function(ro) {
tmp<- ifelse(length(ro[[1]]==0 & !length(ro[[2]])==0),0e+00, ro)
})
v1 <- c( 1e-06,1e-05,0e+00,0e+00,0e+00,1e-07,0e+00)
v2 <- c(4.551651e-38,3.519523e-33,6.316980e-26,8.159048e-34,
4.935429e-20,4.551651e-38,9.080082e-38)
dat <- data.frame(v1, v2)
DataFrame with 7 rows and 2 columns
v1 v2
<numeric> <numeric>
1 1e-06 4.551651e-38
2 1e-05 3.519523e-33
3 0e+00 0e+00
4 0e+00 0e+00
5 0e+00 0e+00
6 1e-07 4.551651e-38
7 0e+00 0e+00
DataFrame with 7 rows and 2 columns
v1 v2
<numeric> <numeric>
1 1e-06 4.551651e-38
2 1e-05 3.519523e-33
3 1e-07 4.551651e-38
How can I get my desired output?
Upvotes: 1
Views: 552
Reputation: 2359
Use grepl function for the second output
dat <- dat[!grepl("^0",dat$v1),]
v1 v2
1 1e-06 4.551651e-38
2 1e-05 3.519523e-33
6 1e-07 4.551651e-38
for first output you can use the same function too
dat$v2 <- ifelse(grepl("^0",dat$v1),0e+00, dat$v2)
dat
v1 v2
1 1e-06 4.551651e-38
2 1e-05 3.519523e-33
3 0e+00 0.000000e+00
4 0e+00 0.000000e+00
5 0e+00 0.000000e+00
6 1e-07 4.551651e-38
7 0e+00 0.000000e+00
Upvotes: 0
Reputation: 340
Not sure if this is what you are looking for:
dat[dat$v1 == 0,][,2] <- 0e+00
dat[dat$v1 != 0,]
Upvotes: 0
Reputation: 3938
As @scoa said:
#show data where v1 equals 0 (0e+00)
dat[dat$v1 == 0,]
v1 v2
3 0 6.316980e-26
4 0 8.159048e-34
5 0 4.935429e-20
7 0 9.080082e-38
#show v2 where v1 equals 0 (0e+00)
dat$v2[dat$v1 == 0]
[1] 6.316980e-26 8.159048e-34 4.935429e-20 9.080082e-38
#Remove rows where v1 equals 0
dat[dat$v1 != 0,]
v1 v2
1 1e-06 4.551651e-38
2 1e-05 3.519523e-33
6 1e-07 4.551651e-38
Upvotes: 0
Reputation: 1400
You need to remove the entries by using !=
v1 <- c( 1e-06,1e-05,0e+00,0e+00,0e+00,1e-07,0e+00)
v2 <- c(4.551651e-38,3.519523e-33,6.316980e-26,8.159048e-34,
4.935429e-20,4.551651e-38,9.080082e-38)
dat <- data.frame(v1, v2)
dat[dat$v1 != 0e+00,]
Upvotes: 1