[英]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
. 现在,我想通过以下方式将全局效率值转换为路径长度值:
path length = 1 / global efficiency
。 I want to do this ONLY if the path length value = NA. 我只想在路径长度值= 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 我们使用
is.na
创建逻辑索引并分配
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
我们也可以用
ifelse
做到这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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.