R-将字符串匹配到字典并替换

时间:2018-12-07 23:17:41

标签: r ggplot2 replace match

我在R中制作条形图,并希望使用我定义的包含更多可读名称的字典来更改x轴字符串。这是代码示例。

#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>

void* getSinAddr(int af, sockaddr *addr)
{
    switch (af)
    {
        case AF_INET:
            return &(reinterpret_cast<sockaddr_in*>(addr)->sin_addr);

        case AF_INET6:
            return &(reinterpret_cast<sockaddr_in6*>(addr)->sin6_addr);
    }
    return NULL;
}

int main()
{
    addrinfo hints = {}, *results, *res;

    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    int m = getaddrinfo(NULL, "2018", &hints, &results);
    if (m < 0)
    {
        std::cout << "getaddrinfo error : " << gai_strerror(m) << std::endl;
        return 1;
    }

    for(res = results; res != NULL; res = res->ai_next)
    {
        char straddr[INET6_ADDRSTRLEN] = {};
        if (inet_ntop(res->ai_family, getSinAddr(res->ai_family, res->ai_addr), straddr, sizeof(straddr)))
            std::cout << "IP - " << straddr << "\n";
        else
            std::cout << "inet_ntop error : " << strerror(errno) << std::endl;
    }

    freeaddrinfo(results);

    return 0;
}

我希望沿x轴显示可读名称。我这样做的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

您可以这样做:

# reverse the vector
convert_vec <- names(readable_strings)
names(convert_vec) <- readable_strings

# replace the values and plot
mydata$name <- sapply(mydata$name, function(x) convert_vec[[x]])
ggplot(mydata, aes(x = name, y=values)) + geom_bar(stat="identity")