使用R中不同变量的值填充变量中的NA值 [英] Populate the NA values in a variable with values from a different variables in R

查看:469
本文介绍了使用R中不同变量的值填充变量中的NA值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似这样的数据

Linking <- data.frame(
ID = c(round((runif(20, min = 10000, max = 99999)), digits = 0), NA, NA, NA, NA),
PSU = c(paste("A", round((runif(20, min = 10000, max = 99999)), digits = 0), sep = ''), NA, NA, NA, NA),
qtr = c(rep(1:10, 2), NA, NA, NA, NA)
)

Linking$Key <- paste(Linking$ID, Linking$PSU, Linking$qtr, sep = "_")
Linking$Key[c(21:24)] <- c("87654_A15467_1", "45623_A23456_2", "67891_A12345_4", "65346_A23987_7")

我想做的是根据键"中的信息填充ID,PSU和qtr的NA值,但仅适用于具有NA值的行.

What I want to do is populate the NA values for ID, PSU, and qtr from the information from "Key", but only for the rows with NA values.

有人知道该怎么做吗?

此代码可以实现我想要的功能,但是它可以对每个变量的所有值执行此操作.我只想对数值为NA的行执行此操作.

This code does what I want, but it does it for all values of each variable. I want to do this just for rows where the values are NA.

Linking2 <- Linking
Linking2$ID <- substr(Linking$Key,1,5)
Linking2$PSU <- substr(Linking$Key,7,12)
Linking2$qtr <- substr(Linking$Key, 14,15)

推荐答案

此处的基本思想是使用逻辑索引向量进行分配.

The basic idea here is to assign using a logical index vector.

Linking$ID[is.na(Linking$ID)] <- substr(Linking$Key,1,5)[is.na(Linking$ID)]

这篇关于使用R中不同变量的值填充变量中的NA值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆