3
Good afternoon !
I am new to R and have a database where I need to include a column, however the values of this column need to be linked to the values of another column.
In case, I have the column ano
(2006:2016) and need to create the column PIB
(with specific values for each year).
The years don’t follow the sequence, some jump.
I’m using dCoopCred$ano
and dCoopCred$PIB
.
Example:
ano PIB
2006 4,0
2007 6,1
2008 5,1
2009 -0,1
2010 7,5
2011 4,0
2012 1,9
2013 3,0
2014 0,5
2015 -3,8
2016 -3,6
However, it’s 10,000 lines, the years don’t follow a sequence.
Sorry anything, it’s my first post here.
Grateful from now on.
Welcome to Stack Overflow English! Your question is not very clear. Do you want the years to be in order? If so:
sort(dCoopCred$ano)
. If not, take a look at how to ask a question here.– Willian Vieira
I don’t understand, the column
PIB
is not the right column?– Rui Barradas
Hello, thank you! The right column is GDP. the column year presents value from 2006 to 2016, but there are 10thousand lines, so they do not follow a sequence. On each year’s line, I want to add its respective GDP value.
– RxT
Possible duplicate of Search for values in one data.frame and add to another (R)
– Daniel Falbel
@Ricardotheodoro marked as duplicate, because I think what you need is a
left_join
.– Daniel Falbel
@Danielfalbel hello! in case, I do not know how to do to take the values of the year and relate them to the value of GDP. In the example you gave, he took two columns with the same values, in my case they are different. I would have to attribute the value of GDP to the year, for example: if the year is 2006, the value of GDP will be 4, if the value of the year is 2012, the value of GDP will be 1.9.
– RxT
@Ricardotheodoro The left Join works like this: you have two tables that have one key in common (in your case, the year) and you want to bring the columns from one table to the other ensuring that the keys match. That’s not what you need?
– Daniel Falbel
@Danielfalbel hello, that’s right ! sorry, I didn’t know how to apply the example to my case. I ended up doing through a for().
dCoopCred$PIB <- c(0)
for(i in row(dCoopCred)){
 if(dCoopCred$ano[i]==2006){
 dCoopCred$PIB[i] <- c(4) 
 }dCoopCred$PIB <- c(0)
for(i in row(dCoopCred)){
 if(dCoopCred$ano[i]==2006){
 dCoopCred$PIB[i] <- c(4) 
 }else if (dCoopCred$ano[i]==2007){
 dCoopCred$PIB[i] <- c(6.1)
 }....
But thank you very much !– RxT
@Ricardotheodoro when you have a while write an example here. Hugs,
– Daniel Falbel