简体   繁体   中英

How to add calculated values to existing column in R

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!

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))
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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM