Append vector not giving names

In R studio, I am looking to create a vector for country names. They are enclosed in my data set in column 1. Countryvec gives factor names

"Australia Australia ..." 

x just gives the names of Russia, country 36, country ends up being

1,1,...,2,2,...,4,4.. etc. 

They are also not in order, 3 ends up between 42 and 43. How do I make the numbers the factors?

gdppc=read.xlsx("H:/dissertation/ALL/YAS.xlsx",sheetIndex = 1,startRow = 1)
countryvec=gdppc[,1]
country=c()
for (j in 1:43){
  x=rep(countryvec[j],25)
  country=append(country,x)
}

1 answer

  • answered 2017-08-16 19:26 manotheshark

    You need to retrieve the levels attribute

    set.seed(7)
    
    v <- factor(letters[rbinom(20, 10, .5)])
    > c(v)
    [1] 6 4 2 2 3 5 3 6 2 4 2 3 5 2 4 2 4 1 6 3
    
    > levels(v)[v]
    [1] "h" "e" "c" "c" "d" "f" "d" "h" "c" "e" "c" "d" "f" "c" "e" "c" "e" "a" "h" "d"
    

    You'll probably need to modify the code to inside the loop:

    x <- rep(levels(countryvec)[countryvec][j], 25)
    

    Or convert the vector prior to the loop:

    countryvec <- levels(countryvec)[countryvec]