如何在R中删除与它们对应的NA和值?

时间:2015-12-08 11:50:18

标签: r na

我的数据包含实验前后的值。例如:

before after
2.5   2.2
3     4
1.8   2.4
NA    3
4     NA

before <- c(2.5 ,3 ,1.8 ,NA ,4)
after <- c(2.2, 4, 2.4, 3 ,NA)

我想要做的是删除NA s以及与之对应的值。在我们的示例中,我想删除将我的数据转换为

NA
before after
2.5   2.2
3     4
1.8   2.4

有什么建议吗?

3 个答案:

答案 0 :(得分:3)

这应该有所帮助:

before <- c(2.5 ,3 ,1.8 ,NA ,4)
after <- c(2.2, 4, 2.4, 3 ,NA)

df = data.frame(before,after)

df = df[complete.cases(df),]

答案 1 :(得分:2)

或使用

public class CidrCompressor
{    
    private readonly Regex _subnetRegex = new Regex(@"^(?<net>\d+\.\d+\.\d+)\.0$", RegexOptions.Compiled); 
    private Regex _currentNetRegex;
    private string _currentNet;
    private int _lastSubIp;

    private List<string> _ipList = new List<string>();

    private void AddReceivedInSubnet()
    {
        for (var i = 0; i < _lastSubIp; ++i)
        {
            _ipList.Add(string.Format("{0}.{1}", _currentNet, i));
        }
        _currentNetRegex = null;
    }

    public void Add(string ip)
    {
        var m = _subnetRegex.Match(ip);
        if (m.Success)
        {
            // Matches *.0
            // Start matching subnet
            _currentNet = m.Groups["net"].Value;
            _currentNetRegex = new Regex(string.Format(@"^{0}\.(?<subIp>\d+)$", _currentNet));          
            _lastSubIp = 0;
        }
        else if (_currentNetRegex != null)
        {
            // Currently matching a subnet
            m = _currentNetRegex.Match(ip);

            if (m.Success)
            {
                var subIp = int.Parse(m.Groups["subIp"].Value);

                if (subIp == _lastSubIp + 1)
                {
                    // See if we have received a full subnet
                    if (subIp == 255)
                    {
                        _ipList.Add(_currentNet + "/24");
                        _currentNetRegex = null;                    
                    }
                    else
                    {
                        _lastSubIp = subIp;
                    }
                }
                else
                {
                    // Not continuous so add indivudial IPs
                    AddReceivedInSubnet();
                    Add(ip);
                }
            }
            else
            {
                // Received IP in different net before .255
                // Add all IPs received
                AddReceivedInSubnet();

                // Process ip we received
                Add(ip);
            }
        }
        else
        {
            _ipList.Add(ip);
        }
    }

    public IEnumerable<string> IpList 
    {
        get
        {
            return _ipList;
        }
    }
}

答案 2 :(得分:1)

或者您可以使用na.omit(由Roland评论)

df = data.frame(before,after)
df = na.omit(df)