Reputation: 11
I have a data frame (file), which has two columns:
Path length: 0.5; 0.5; NA; 5; NA; 8; NA
Global efficiency: NA; NA; 0.8; 0.2; 0.3; NA; NA
Now I want to convert the global efficiency values into path length values by: path length = 1 / global efficiency
. I want to do this ONLY if the path length value = NA. Then I want to add the calculated path lengths to the existing column 'path length'. Any help how to do that?
I already did:
ifelse(file$P_L_Mean != 'NA')
{
file$P_L_Mean <- 1/file$P_Eglob_Mean
}
But this does not add the values to the existing column...
Thanks!
Upvotes: 1
Views: 738
Reputation: 103
X=data.frame(path_length=c(0.5,0.5,NA,5,NA,8),global_eff=c(NA,NA,0.8,0.2,0.3,NA))
fun=Vectorize(function(x,y){if (is.na(x)){return(1/y)}})
X= X %>% mutate(global_eff_2=fun(path_length,global_eff))
Upvotes: 1
Reputation: 887831
We create a logical index with is.na
and assign
i1 <- is.na(file$P_L_Mean)
file$P_L_Mean[i1] <- 1/file$P_Eglob_Mean[i1]
We can also do this with ifelse
file$P_L_Mean <- with(file, ifelse(is.na(P_L_Mean), 1/P_Eglob_Mean, P_L_Mean))
Upvotes: 1